Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I drop all the default constraints constraints on a table

How can I drop all the default constraints belonging to a particular table in SQL 2005?

like image 608
Vinay Pandey Avatar asked Apr 20 '09 07:04

Vinay Pandey


People also ask

How do I drop all constraints in a table?

To drop (table) check constraints, use the DROP CHECK clause of the ALTER TABLE statement. When you drop a check constraint, all packages and cached dynamic statements with INSERT or UPDATE dependencies on the table are invalidated. The name of all check constraints on a table can be found in the SYSCAT.

How drop all constraints on all tables in SQL Server?

Easy way is use sp_help tablename. All constraints will be listed. Then use ALTER TABLE DROP CONSTRAINT to drop them.

Can I remove the DEFAULT constraint columns in SQL Server?

The DROP DEFAULT command is used to delete a DEFAULT constraint.

How do I change the DEFAULT constraint in a table?

To add a DEFAULT constraint to an existing column, use the ALTER TABLE statement and specify the column and the specific constraint that you want to apply.


1 Answers

One solution from a search: (Edited for Default constraints)

SET NOCOUNT ON

DECLARE  @constraintname SYSNAME, @objectid int,
           @sqlcmd         VARCHAR(1024)

DECLARE CONSTRAINTSCURSOR CURSOR  FOR
SELECT NAME, object_id
FROM   SYS.OBJECTS
WHERE  TYPE = 'D' AND @objectid = OBJECT_ID('Mytable')

OPEN CONSTRAINTSCURSOR

FETCH NEXT FROM CONSTRAINTSCURSOR
INTO @constraintname, @objectid

WHILE (@@FETCH_STATUS = 0)
BEGIN
    SELECT @sqlcmd = 'ALTER TABLE ' + OBJECT_NAME(@objectid) + ' DROP CONSTRAINT ' + @constraintname
    EXEC( @sqlcmd)
    FETCH NEXT FROM CONSTRAINTSCURSOR
    INTO @constraintname, @objectid
END

CLOSE CONSTRAINTSCURSOR
DEALLOCATE CONSTRAINTSCURSOR
like image 74
gbn Avatar answered Sep 29 '22 12:09

gbn