在SQL Server中,默认值被定义为在一个特定的列相关联的约束表。所有约束都被分配一个名称;这很重要,因为一旦约束被创建,如果你想修改它,你必须通过这个名字来引用它。基于此示例表(我会看这个问题,看看如果我错了。)
:
CREATE TABLE MyTable
(
MyTableId int not null
,SomeData varchar(50) not null default 'Foo'
,MoreData datetime not null default CURRENT_TIMESTAMP
)
第1步:确定是否在列上存在约束。有几种方法可以做到这一点,都涉及系统视图和/或元数据功能。这里有一个快速,其中“MyTable的”和“SomeData”可以作为参数来设定:
SELECT name
from sys.default_constraints
where parent_object_id = object_id('MyTable')
and parent_column_id = columnproperty(object_id('MyTable'), 'SomeData', 'ColumnId')
试试吧,你会发现所产生的名字基本上是随机的废话。要确定是否在列上存在一个默认的,你可以这样做:
IF exists (select name
from sys.default_constraints
where parent_object_id = object_id('MyTable')
and parent_column_id = columnproperty(object_id('MyTable'), 'SomeData', 'ColumnId'))
PRINT 'Default found'
ELSE
PRINT 'NoDefault'
要删除现有的默认,你不知道这个名字,你就必须建立动态SQL。 (引用的文章中的代码是错误的,并明确从来没有测试。)@ CALIN确实稍微不同于我会做到这一点,但这个想法是一样的:
DECLARE @Command nvarchar(max)
SELECT @Command = 'ALTER TABLE MyTable drop constraint ' + name
from sys.default_constraints
where parent_object_id = object_id('MyTable')
and parent_column_id = columnproperty(object_id('MyTable'), 'SomeData', 'ColumnId')
IF @Command is not null
EXECUTE sp_executeSQL @Command
(错误检查,对于参数表和列进行检查,等等)
最后,就可以避免大部分的这种通过在创建约束,像这样命名的默认值:
CREATE TABLE MyTable
(
MyTableId int not null
,SomeData varchar(50) not null
constraint DF_MyTable__SomeData default 'Foo'
,MoreData datetime not null
constraint DF_MyTable__MoreData default CURRENT_TIMESTAMP
)
或者像这样:
IF not exists (select name
from sys.default_constraints
where parent_object_id = object_id('MyTable')
and parent_column_id = columnproperty(object_id('MyTable'), 'SomeData', 'ColumnId'))
ALTER TABLE MyTable
add constraint DF_MyTable__SomeData
default 'Foo' for SomeData
你肯定会'ALTER'你的桌子,因为它是修改其结构的唯一方法。 – 2012-03-07 14:41:10
哪一列?你有两列有默认值。该方法将是相同的,只是想确保明确的例子正在处理你正在谈论的专栏。 – 2012-03-07 14:53:58