2012-07-27 117 views
1

我正在嘗試編寫一個過程以更快地從任何表中刪除唯一約束。刪除唯一約束的過程

IF EXISTS 
     (SELECT * 
     FROM dbo.sysobjects 
     WHERE id = object_id(N'[dba].[spu_drop_uq_index]')) 
    DROP PROCEDURE [dba].[spu_drop_uq_index] 
GO 

CREATE PROCEDURE [dba].[spu_drop_uq_index] (@table varchar(1000), @index varchar(1000)) 
AS 
BEGIN 
    DECLARE @sql varchar(1000) 
    SET @sql = 'ALTER TABLE ['[email protected]+'] DROP CONSTRAINT ['[email protected]+']' 
    IF EXISTS (SELECT name FROM sysindexes WHERE name = @index) 
     EXEC @sql 
END  
GO 

EXEC [dba].[spu_drop_uq_index] @table = 'aaa', @index = 'UQ_xxx' 
GO 

但我得到一個錯誤:

The name 'ALTER TABLE [aaa] DROP CONSTRAINT [UQ_xxx]' is not a valid identifier. 

但是,如果我執行這個不是動態的,它成功:

ALTER TABLE [aaa] DROP CONSTRAINT [UQ_xxx] 

我在做什麼錯? :) 謝謝!

回答

3

使用

exec sp_executesql @sql 

,而不是EXEC,或放在括號中的@sql

Exec (@sql) 

sp_executesql優先:http://msdn.microsoft.com/en-us/library/ms175170(v=sql.105).aspx

To execute a string, we recommend that you use the sp_executesql stored procedure instead of the EXECUTE statement. Because this stored procedure supports parameter substitution, sp_executesql is more versatile than EXECUTE; and because sp_executesql generates execution plans that are more likely to be reused by SQL Server, sp_executesql is more efficient than EXECUTE.

+0

我太親近了!非常感謝您指出這一點! :)) – 2012-07-27 10:43:00

+2

@AndriusNaruševičius另外,使用quotename而不是手動添加[] – podiluska 2012-07-27 10:44:36

1

裹在括號中的EXEC字符串:

EXEC (@sql) 

執行動態字符串時,需要括號。執行sprocs時,它們不是。