Drop default constraint on a column in TSQL

前端 未结 3 630
没有蜡笔的小新
没有蜡笔的小新 2020-12-28 12:01

I have a table with a column like this that is currently live:

name NVARCHAR(128) NOT NULL DEFAULT \'\'
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-28 13:02

    I would like to refer a previous question, Because I have faced same problem and solved by this solution. First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

    DECLARE @Command NVARCHAR(MAX)
         declare @table_name nvarchar(256)
         declare @col_name nvarchar(256)
         set @table_name = N'ProcedureAlerts'
         set @col_name = N'EmailSent'
    
         select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
         from 
             sys.tables t
             join sys.default_constraints d on d.parent_object_id = t.object_id
             join sys.columns c on c.object_id = t.object_id
                                   and c.column_id = d.parent_column_id
         where 
             t.name = @table_name
             and c.name = @col_name) + ']'
    
        --print @Command
        exec sp_executesql @Command
    

    It will drop your default constraint. However if you want to create it again you can simply try this

    ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]
    

    Finally, just simply run a DROP command to drop the column.

提交回复
热议问题