Question

I am trying to write a procedure to drop the Unique constraints from any table quicker.

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 ['+@table+'] DROP CONSTRAINT ['+@index+']'
    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

But I get an error:

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

However, if I execute this not dynamically, it succeeds:

ALTER TABLE [aaa] DROP CONSTRAINT [UQ_xxx]

What am I doing wrong? :) Thanks!

Was it helpful?

Solution

Use

 exec sp_executesql @sql

instead of EXEC, or put the @sql in parenthesis

 Exec (@sql)

sp_executesql is preferred: 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.

OTHER TIPS

Wrap the exec string in brackets:

EXEC  (@sql)

When executing dynamic strings, brackets are required. When executing sprocs, they're not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top