How do you drop a default value or similar constraint in T-SQL?

后端 未结 6 598
萌比男神i
萌比男神i 2020-12-02 18:26

I know the syntax:

ALTER TABLE [TheTable] DROP CONSTRAINT [TheDefaultConstraint]

but how to I drop the default constraint when I don\'t kno

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 18:29

    For a single table and column in a single line use the following

    declare @sql nvarchar(max); set @sql = ''; SELECT @sql+='ALTER TABLE [dbo].[YOURTABLENAME] DROP CONSTRAINT ' + ((SELECT OBJECT_NAME(constid) FROM sysconstraints WHERE OBJECT_NAME(id) = 'YOURTABLENAME'AND colid IN (SELECT ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS Where Table_Name = 'YOURTABLENAME' and COLUMN_NAME = 'YOURCOLUMNNAM'))) + ';'; EXEC sp_executesql @sql;
    

    If you have multiple constraints on the column you will need to discriminate on the constraint you are after, but if you just have a default constraint this will do the trick.

    Check out the other columns available in the information_schema to allow you to discriminate further.

提交回复
热议问题