SQL Server 2005 drop column with constraints

后端 未结 13 991
一向
一向 2020-12-07 23:54

I have a column with a \"DEFAULT\" constraint. I\'d like to create a script that drops that column.

The problem is that it returns this error:

Msg 50         


        
13条回答
  •  伪装坚强ぢ
    2020-12-08 00:46

    Just to build on Jeremy Stein's answer, I created a stored procedure for this, and set it up so it can be used to delete a column that has or does not have default constraints. It's not real efficient since it's querying sys.columns twice, but it works.

    CREATE PROCEDURE [dbo].[RemoveColumnWithDefaultConstraints] 
        -- Add the parameters for the stored procedure here
        @tableName nvarchar(max), 
        @columnName nvarchar(max)
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;
    
        DECLARE @ConstraintName nvarchar(200)
        SELECT @ConstraintName = Name 
        FROM SYS.DEFAULT_CONSTRAINTS 
        WHERE PARENT_OBJECT_ID = OBJECT_ID(@tableName) 
            AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns WHERE NAME = (@columnName) 
            AND object_id = OBJECT_ID(@tableName))
        IF @ConstraintName IS NOT NULL
            EXEC('ALTER TABLE ' + @tableName + ' DROP CONSTRAINT ' + @ConstraintName)
    
        IF EXISTS(SELECT * FROM sys.columns WHERE Name = @columnName  
            AND Object_ID = Object_ID(@tableName))
            EXEC('ALTER TABLE ' + @tableName + ' DROP COLUMN ' + @columnName)       
    END
    GO
    

提交回复
热议问题