刪除SQL約束的方法
在SQL數(shù)據(jù)庫中,如果需要刪除表約束,應該如何操作呢?下面就將為您介紹刪除SQL表約束的方法,供您參考,希望對您有所幫助。
1)禁止所有表約束的SQL
select 'alter table '+name+' nocheck constraint all' from sysobjects where type='U'
2)刪除所有表數(shù)據(jù)的SQL
select 'TRUNCATE TABLE '+name from sysobjects where type='U'
3)恢復所有表約束的SQL
select 'alter table '+name+' check constraint all' from sysobjects where type='U'
4)刪除某字段的約束
declare @name varchar(100)
--DF為約束名稱前綴
select @name=b.name from syscolumns a,sysobjects b where a.id=object_id('表名') and b.id=a.cdefault and a.name='字段名' and b.name like 'DF%'
--刪除約束
alter table 表名 drop constraint @name
--為字段添加新默認值和約束
ALTER TABLE 表名 ADD CONSTRAINT @name DEFAULT (0) FOR [字段名]對字段約束進行更改
--刪除約束
ALTER TABLE tablename
Drop CONSTRAINT 約束名
--修改表中已經(jīng)存在的列的屬性(不包括約束,但可以為主鍵或遞增或唯一)
ALTER TABLE tablename
alter column 列名 int not null
--添加列的約束
ALTER TABLE tablename
ADD CONSTRAINT DF_tablename_列名 DEFAULT(0) FOR 列名
--添加范圍約束
alter table tablename add check(性別 in ('M','F'))
【編輯推薦】