1. 程式人生 > >sqlserver刪除約束和動態約束

sqlserver刪除約束和動態約束

SQL資料庫中,如果需要刪除表約束,應該如何操作呢?下面就將為您介紹刪除SQL表約束的方法,供您參考,希望對您有所幫助。

1)禁止所有表約束的SQL
select 'alter table '+name+' nocheck constraint all' from sysobjects where type='U'

2)刪除所有表資料的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%'

或者:(select @name=a.name,a.* from sys.objects a
inner join sys.columns b on b.default_object_id = a.object_id
where a.name like 'DF%' and b.name = '欄位名' and b.object_id = object_id('表名'))
--刪除約束
alter table 表名 drop constraint @name
--為欄位新增新預設值和約束
ALTER TABLE 表名 ADD CONSTRAINT @name  DEFAULT (0) FOR [欄位名]對欄位約束進行更改
--刪除約束
ALTER TABLE tablename
Drop CONSTRAINT 約束名
--修改表中已經存在的列的屬性(不包括約束,但可以為主鍵或遞增或唯一)
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'))