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.)
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.)
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.
You can find the name of the constraint out by sp_help [table name] and then drop it by name.
Or you can probably do this via Management studio.
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.