首页 > 技术文章 > sql server 修改表的默认值, 需要先删除约束条件

zhangzhifeng 2015-09-16 10:27 原文

---------增加是否发布订单
if not exists(select 1 from syscolumns where name='iIsRelease' and id=OBJECT_ID('MCYD'))
begin
ALTER TABLE MCYD ADD iIsRelease INTEGER DEFAULT 1;
END
GO

UPDATE mcyd SET iIsRelease = 1 WHERE iIsRelease IS NULL
GO


declare @name varchar(100)
--DF为约束名称前缀
select @name=b.name from syscolumns a,sysobjects b where a.id=object_id('mcyd')
and b.id=a.cdefault and a.name='iIsRelease' and b.name like 'DF%'
--删除约束
exec('alter table mcyd drop constraint '+ @name)
ALTER TABLE mcyd ALTER COLUMN iIsRelease INTEGER
--为字段添加新默认值和约束
exec('ALTER TABLE mcyd ADD CONSTRAINT '+@name +' DEFAULT (1) FOR [iIsRelease]')

推荐阅读