我有一个表,其中一列是类型为datetime的“日期”。我们决定向该列添加一个默认约束

Alter table TableName
alter column dbo.TableName.Date default getutcdate() 

但这给了我错误:

'.'附近语法错误。

有人看到这里有什么明显的错误吗,这是我遗漏的(除了为列取一个更好的名字)


当前回答

实际上,你必须做下面的例子,这将有助于解决问题…

drop table ABC_table

create table ABC_table
(
    names varchar(20),
    age int
)

ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names

insert into ABC(age) values(10)

select * from ABC

其他回答

试试这个

alter table TableName 
 add constraint df_ConstraintNAme 
 default getutcdate() for [Date]

例子

create table bla (id int)

alter table bla add constraint dt_bla default 1 for id



insert bla default values

select * from bla

还要确保你为默认的约束命名,因为它会有一个疯狂的系统生成的名字,所以以后放弃它将是一件痛苦的事情。参见如何命名默认约束以及如何在SQL Server中删除没有名称的默认约束

实际上,你必须做下面的例子,这将有助于解决问题…

drop table ABC_table

create table ABC_table
(
    names varchar(20),
    age int
)

ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names

insert into ABC(age) values(10)

select * from ABC

我确认像JohnH的评论一样,永远不要在你的对象名称中使用列类型! 这是令人困惑的。尽可能使用括号。

试试这个:

ALTER TABLE [TableName]
ADD  DEFAULT (getutcdate()) FOR [Date]; 

您指定了两次表名。ALTER TABLE部分为表命名。 试一试: 修改表TableName alter column [Date] default gettcdate

修改表TableName drop constraint DF_TableName_WhenEntered

修改表TableName 添加约束DF_TableName_WhenEntered 默认的getutcdate()为WhenEntered