sql server 字段设置约束

一.给字段添加默认值

语法:

alter table 表名 add constraint 约束名字 DEFAULT 默认值 for 字段名称

例:

alter table WD_Platform add constraint DF_WD_Platform_Platform_UID DEFAULT '' for Platform_UID


二.查找某字段默认约束名称

declare @constraint_name varchar(100)


select @constraint_name =obj.name from syscolumns as col
join sysobjects as obj on obj.id=col.cdefault
where col.id=object_id('WD_Platform') and col.name='Platform_UID'
select @constraint_name

说明: syscolumns用户数据库所定义的标字段都出在此.

sysobjects:用户数据库所定义的表,主键,外键,约束等都存放在这张系统表.


三.判断是否存在莫约束

if exists(select top 1 1 from sysobjects where name='DF_WD_Platform_Platform_UID') begin
    select 约束存在
end

四.删除约束

ALTER TABLE WD_Platform  DROP CONSTRAINT DF_WD_Platform_Platform_UID

备注约束不能直接修改,如果需要更改约束值,请先删除后,再创建.

你可能感兴趣的:(sql)