SQL Server:删除约束(如果存在)

时间:2016-10-15 17:44:40

标签: sql sql-server

我现在一直在努力争取这个约2个小时。我正在尝试使用存储过程创建表的列。也就是说,我必须检查该列是否存在,如果存在,我必须删除它。

问题是我无法删除约束,我收到错误:

  

无效的列名'RowNumber'

代码:

DECLARE @tableName NVARCHAR(30)
DECLARE @newColumnName NVARCHAR(100)
DECLARE @newDefaultValue NVARCHAR(100)
DECLARE @newColumnType NVARCHAR(100)
DECLARE @constraintName NVARCHAR (30)

SET @tableName='TestTable'
SET @newDefaultValue = 'James'
SET @newColumnType ='NVARCHAR(100)'
SET @newColumnName = 'James'

CREATE TABLE #cons (constraintName NVARCHAR(100), RowNumber int)

INSERT INTO #cons(constraintName, RowNumber)
    SELECT 
        t.*
    FROM 
        (SELECT 
             name, 
             ROW_NUMBER() OVER(ORDER BY name) AS RowNumber 
         FROM 
             sys.objects 
         WHERE 
             type_desc LIKE '%CONSTRAINT' 
             AND name like '%JAMES%'  
             AND name like '%JAMES%') AS t

    SELECT * FROM #cons

    IF EXISTS(SELECT * 
              FROM INFORMATION_SCHEMA.COLUMNS 
              WHERE TABLE_NAME = '[dbo].[TestTable]' 
                AND COLUMN_NAME = 'James') 
    BEGIN
        DECLARE @i int
        DECLARE @numberOfRows int

        SET @i = 1
        SET @numberOfRows = (SELECT COUNT(*) FROM #cons)

        WHILE(@i <= @numberOfRows)
        BEGIN
            SET @constraintName = (SELECT constraintName 
                                   FROM #cons 
                                   WHERE RowNumber = @i)

            DECLARE @dropStatement NVARCHAR(500)
            SET @dropStatement = 'ALTER TABLE [dbo].[TestTable] DROP CONSTRAINT ' + @constraintName

            EXEC(@dropStatement)

            SET @i = @i + 1
        END                                     

        ALTER TABLE [dbo].[TestTable] 
        DROP COLUMN [James]
    END 

    --ALTER TABLE [dbo].[TestTable] ADD James NVARCHAR(50) 
    DROP TABLE #cons

如何让这个删除列?

1 个答案:

答案 0 :(得分:-2)

ALTER TABLE DROP CONSTRAINT @constraintname

在drop colum之前