Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know the syntax:

ALTER TABLE [TheTable] DROP CONSTRAINT [TheDefaultConstraint] 

but how to I drop the default constraint when I don't know its name? (That is, it was autogenerated at CREATE TABLE time.)

like image 681
Frank Krueger Avatar asked Jul 14 '09 01:07

Frank Krueger


People also ask

How do I drop a default constraint?

Syntax: ALTER TABLE <table_name> ALTER COLUMN <column_name> DROP DEFAULT; Example: Lets say we want to drop the constraint from STUDENTS table, which we have created in the above sections.

How do I drop a default value in a column in SQL?

Before dropping a default, unbind the default by executing sp_unbindefault if the default is currently bound to a column or an alias data type. After a default is dropped from a column that allows for null values, NULL is inserted in that position when rows are added and no value is explicitly supplied.

Can we drop a constraint in SQL?

You can delete a check constraint in SQL Server by using SQL Server Management Studio or Transact-SQL. Deleting check constraints removes the limitations on data values that are accepted in the column or columns included in the constraint expression.


2 Answers

You can use this code to do it automatically:

DECLARE @tableName VARCHAR(MAX) = '<MYTABLENAME>' DECLARE @columnName VARCHAR(MAX) = '<MYCOLUMNAME>' 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) 

Just replace <MYTABLENAME> and <MYCOLUMNNAME> as appropriate.

like image 184
Polemarch Avatar answered Oct 15 '22 08:10

Polemarch


If you want to do this manually, you can use Management Studio to find it (under the Constraints node inside the table).

To do it using SQL:

  • If the constraints are default constraints, you can use sys.default_constraints to find it:

    SELECT OBJECT_NAME(parent_object_id) AS TableName, name AS ConstraintName FROM sys.default_constraints ORDER BY TableName, ConstraintName 
  • If you are looking for other constraints as well (check, unique, foreign key, default, primary key), you can use sysconstraints:

    SELECT OBJECT_NAME(id) AS TableName, OBJECT_NAME(constid) AS ConstraintName FROM sysconstraints ORDER BY TableName, ConstraintName 

You do not say which version of SQL Server you are using. The above work on both SQL 2005 and SQL 2008.

like image 44
adrianbanks Avatar answered Oct 15 '22 07:10

adrianbanks