新聞中心
sql server默認(rèn)約束可不能小看,它影響著我們的刪除字段操作,可能會(huì)造成刪除字段時(shí)報(bào)錯(cuò)。

讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來自于我們對(duì)這個(gè)行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長期合作伙伴,公司提供的服務(wù)項(xiàng)目有:域名與空間、虛擬空間、營銷軟件、網(wǎng)站建設(shè)、愛民網(wǎng)站維護(hù)、網(wǎng)站推廣。
在SQL Server 中,如果給表的一個(gè)字段設(shè)置了默認(rèn)值,就會(huì)在系統(tǒng)表sysobjects中生成一個(gè)sql server默認(rèn)約束。如果想刪除這個(gè)設(shè)置了默認(rèn)值的字段(假設(shè)此字段名column1),執(zhí)行“ALTER TABLE table1 DROP COLUMN column1”時(shí)就會(huì)報(bào)錯(cuò):
- The object 'DF__xxxxxxxxxxx' is dependent on column 'column1'.
- ALTER TABLE DROP COLUMN column1failed because one or more objects access this column.
所以在刪除此字段時(shí)需要先將系統(tǒng)表中的對(duì)應(yīng)默認(rèn)約束刪除, 可以使用下面的腳本進(jìn)行刪除sql server默認(rèn)約束:
- 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)
在刪除對(duì)應(yīng)的默認(rèn)約束后,執(zhí)行:
- ALTER TABLE table1 DROP COLUMN column1
即可刪除字段。
【編輯推薦】
SQL Server外關(guān)鍵字約束的定義
修改Sql Server唯一約束
sql server中動(dòng)態(tài)sql語句的應(yīng)用
SQL Server刪除視圖的兩種方法
SQL Server視圖的使用
本文標(biāo)題:刪除sqlserver默認(rèn)約束的通用腳本
URL網(wǎng)址:http://www.dlmjj.cn/article/dpepcco.html


咨詢
建站咨詢
