sql server 2008 删除表的 constraints

给定表名和列名删除列上的约束

抄来一段

DECLARE @tablename VARCHAR(100), @columnname VARCHAR(100), @tab VARCHAR(100)  
SET @tablename='CountryGroupEmailAndWaitAux' 
SET @columnname='actionOfHasNoValidEmail' 
declare @defname varchar(100)  
declare @cmd varchar(100)  
select @defname = name  
FROM sysobjects so   
JOIN sysconstraints sc  
ON so.id = sc.constid  
WHERE object_name(so.parent_obj) = @tablename  
AND so.xtype = 'D' 
AND sc.colid =  
(SELECT colid FROM syscolumns  
WHERE id = object_id(@tablename) AND  
name = @columnname)  
select @cmd='alter table '+ @tablename+ ' drop constraint '+ @defname  
if @cmd is null print 'No default constraint to drop'  
exec (@cmd) 

由于实际应用里,需要改动表中大量字段的长度等属性,索性把约束都删掉重建了

改了下

给定表名直接删除所有的约束

USE [testdatabase]
DECLARE
@tablename VARCHAR(100), @columnname VARCHAR(100), @coname VARCHAR(100) SET @tablename='testtable1' declare @cmd varchar(100) declare test_cursor cursor for select so.name as coname, sco.name as columnname FROM sysobjects so JOIN sysconstraints sc ON so.id = sc.constid inner join syscolumns sco on sc.colid = sco.colid WHERE object_name(so.parent_obj) = @tablename AND so.xtype = 'D' AND sco.id = OBJECT_ID(@tablename) open test_cursor fetch next from test_cursor into @coname , @columnname WHILE @@FETCH_STATUS = 0 BEGIN select @cmd='alter table '+ @tablename+ ' drop constraint '+ @coname if @cmd is null print 'No default constraint to drop' print @cmd --exec (@cmd) --去掉注释既可执行 FETCH NEXT FROM test_cursor into @coname , @columnname END CLOSE test_cursor DEALLOCATE test_cursor

 

你可能感兴趣的:(sql server 2008 删除表的 constraints)