现在的位置: 首页 > 综合 > 正文

SQL Server 临时禁用和启用所有外键约束

2013年09月11日 ⁄ 综合 ⁄ 共 1419字 ⁄ 字号 评论关闭

--获得禁用所有外键约束的语句
select  'ALTER TABLE ['  + b.name +  '] NOCHECK CONSTRAINT ' +  a.name +';' as  禁用约束  

from  sysobjects  a ,sysobjects  b    
where  a.xtype ='f' and  a.parent_obj = b.id

--获得启用所有外键约束的语句
select  'ALTER TABLE [' + b.name +  '] CHECK CONSTRAINT ' +  a.name +';' as  启用约束    

from  sysobjects  a ,sysobjects  b    
where  a.xtype ='f' and  a.parent_obj = b.id

 

[代码] SQL Server禁止全部约束应用到数据表

1 ALTERTABLEtb1
2 NOCHECK CONSTRAINTALL
3 GO

[代码] SQL Server解禁全部约束应用到数据表

1 ALTERTABLEtb1
2 CHECKCONSTRAINTALL
3

GO

SQL约束控制
 
1)
禁止所有表约束的SQL
 
select ''alter table ''+name+'' nocheck constraint all'' fromwhere type=''U''
 
 
2)
删除所有表数据的SQL
 
select ''TRUNCATE TABLE ''+name from sysobjects ''
 
 
3)
恢复所有表约束的SQL
 
select ''alter table ''+name+'' check constraint all'' from type=''U''
 
 
4)
删除某字段的约束
 
declare @name varchar(100)
 
--DF
为约束名称前缀
 
selectb.name from syscolumns a,sysobjects b where a.id=object_id(''
表名'') and b.id=a.cdefault ''字段名'' and b.name like ''DF%''

 
--
删除约束
 
alter table
表名 drop constraint @name
 
为字段添加新默认值和约束
 
ALTER TABLE
表名 ADD CONSTRAINT @name DEFAULT (0) FOR [
 
 
对字段约束进行更改
 
--
删除约束
 
ALTER TABLE tablename
 
Drop CONSTRAINT
约束名
 
--
修改表中已经存在的列的属性(不包括约束,但可以为主键或递增或唯一)
 
ALTER column
列名 int not null
 
--
添加列的约束
 
ALTER TABLE tablename
 
ADD CONSTRAINT DF_tablename_
列名 DEFAULT(0) FOR 列名
 
--
添加范围约束
 
alter table tablename (''M'',''F''))

SQL 禁用开启表的所有约束 2000
--禁用所有约束
exec sp_msforeachtable "alter table ? nocheck CONSTRAINT all"
--再启用所有外键约束

exec sp_msforeachtable "alter table ? check constraint all"

2005
EXEC dbo.sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'

EXEC dbo.sp_MSforeachtable 'ALTER TABLE ? CHECK CONSTRAINT ALL'

抱歉!评论已关闭.