2012-07-27 2 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, 또는 넣어

Exec (@sql) 

sp_executesql가 바람직하고 괄호 안에 @sql : 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

너무 가깝습니다. 이 점을 지적 해 주셔서 감사합니다! :)) –

+2

@ AndriusNaruševičius 또한 수동으로 []를 추가하는 대신 quotesename을 사용하십시오. – podiluska

1

랩 괄호 안의 간부 문자열 :

EXEC (@sql) 

동적 문자열을 실행할 때 대괄호가 필요합니다. sprocs를 실행할 때, 그들은 그렇지 않습니다.

관련 문제