Wednesday, March 27, 2013

Sql script to drop all constraints on a table

-- t-sql script let to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)

declare @i int
set @i=1

while @i<46 br="">begin

SELECT @database = DB_NAME()
set @table = 'dnt_posts'+ convert(varchar(2),@i)
DECLARE @sql nvarchar(255)
WHILE EXISTS(SELECT OBJECT_NAME(OBJECT_ID) AS CONSTRAINT_NAME FROM sys.objects WHERE type_desc LIKE 'DEFAULT_CONSTRAINT' AND OBJECT_NAME(parent_object_id) = @table)
BEGIN
  SELECT  @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + OBJECT_NAME(OBJECT_ID)
  FROM sys.objects WHERE type_desc LIKE 'DEFAULT_CONSTRAINT' AND OBJECT_NAME(parent_object_id) = @table
exec    sp_executesql @sql
END

set @i=@i+1
end

Go