我收到错误说:
附近的语法不正确。
CREATE TABLE Test (ID INT not null IDENTITY Primary key,
CreatedBy VARCHAR(20) not null,
CreatedDate DATETIME not null,
UpdatedBy VARCHAR(20) not null,
LastUpdated DATETIME not null,
CONSTRAINT Test_CreatedBy DEFAULT USER_NAME() FOR CreatedBy,
CONSTRAINT Test_CreatedDate DEFAULT GETDATE() FOR CreatedDate,
CONSTRAINT Test_UpdatedBy DEFAULT USER_NAME() FOR UpdatedBy,
CONSTRAINT Test_LastUpdated DEFAULT GETDATE() FOR LastUpdated)
go
答案 0 :(得分:1)
您可以将约束定义为列级别,如下所示
CREATE TABLE Test (
ID INT NOT NULL IDENTITY(1,1) Primary key,
CreatedBy VARCHAR(20) NOT NULL DEFAULT USER_NAME(),
CreatedDate DATETIME NOT NULL DEFAULT GETDATE(),
UpdatedBy VARCHAR(20) NOT NULL DEFAULT USER_NAME(),
LastUpdated DATETIME NOT NULL DEFAULT GETDATE());
GO
答案 1 :(得分:1)
试试这个语法:
CREATE TABLE Test
(
ID INT not null IDENTITY Primary key,
CreatedBy VARCHAR(20) not null
CONSTRAINT Test_CreatedBy DEFAULT USER_NAME(),
CreatedDate DATETIME not null
CONSTRAINT Test_CreatedDate DEFAULT GETDATE(),
UpdatedBy VARCHAR(20) not null
CONSTRAINT Test_UpdatedBy DEFAULT USER_NAME(),
LastUpdated DATETIME not null
CONSTRAINT Test_LastUpdated DEFAULT GETDATE()
);
GO
dbfiddle here
或者如果您更喜欢使用ALTER TABLE:
CREATE TABLE Test
(
ID INT not null IDENTITY Primary key,
CreatedBy VARCHAR(20) not null,
CreatedDate DATETIME not null,
UpdatedBy VARCHAR(20) not null,
LastUpdated DATETIME not null
);
GO
ALTER TABLE Test
ADD CONSTRAINT Test_CreatedBy DEFAULT USER_NAME() FOR CreatedBy;
GO
ALTER TABLE Test
ADD CONSTRAINT Test_CreatedDate DEFAULT GETDATE() FOR CreatedDate;
GO
ALTER TABLE Test
ADD CONSTRAINT Test_UpdatedBy DEFAULT USER_NAME() FOR UpdatedBy;
GO
ALTER TABLE Test
ADD CONSTRAINT Test_LastUpdated DEFAULT GETDATE() FOR LastUpdated;
GO
dbfiddle here