示例
A. 将默认值绑定到列
假定已经用 CREATE DEFAULT 语句在当前数据库中定义了名为 today 的默认值,此示例将默认值绑定到 employees 表的 hire date 列。当将行添加到 employees 表而且没有提供 hire date 列的数据时,列取得默认值 today 的值。
USE master
EXEC sp_bindefault 'today', 'employees.[hire date]'
C. 使用 futureonly_flag
此示例将默认值 def_ssn 绑定到用户定义的数据类型 ssn。因为已指定 futureonly,所以不影响类型 ssn 的现有列。
USE master
EXEC sp_bindefault 'def_ssn', 'ssn', 'futureonly'
D. 使用分隔标识符
此示例显示了在 object_name 中分隔标识符的使用。
USE master
CREATE TABLE [t.1] (c1 int)
-- Notice the period as part of the table name.
EXEC sp_bindefault 'default1', '[t.1].c1'
-- The object contains two periods;
-- the first is part of the table name,
-- and the second distinguishes the table name from the column name.
----a.先删除要处理字段的默认值约束
declare @s varchar(8000)
set @s=''
select @s=@s+'
alter table ['+b.name+'] drop constraint ['+d.name+']'
from syscolumns a
join sysobjects b on a.id=b.id
join syscomments c on a.cdefault=c.id
join sysobjects d on c.id=d.id
where b.name='t1'
and (a.name='name' or a.name='memo')
exec(@s)
----b.再删除字段 name
alter table t1 drop column [name]
----c.修改字段 memo
alter table t1 alter column [memo] varchar(32)
----d.为字段 memo 添加默认值约束
set @s='alter table t1 add constraint
[df__t1__memo__'+cast(newid() as varchar(36))
+'] default (32) for memo'
exec(@s)
go
--插入数据测试
insert t1 values(default,default)
select * from t1
go
--删除测试
drop table t1
/*--测试结果
ID Memo
----------- --------------------------------
0 32