你的语法有点不对劲:
CREATE TRIGGER dbo.trUpdate
ON dbo.Tablename
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE Tablename
SET Datecolumn = GETDATE()
WHERE ID IN (SELECT id FROM inserted);
END
GO
现在您应该做的是将列更改为NOT NULL
默认值GETDATE()
。然后你只需要在更新时触发这个触发器。
-- first clean up any remaining NULL values:
UPDATE dbo.Tablename
SET DateColumn = '19000101'
WHERE DateColumn IS NULL;
-- now add the default constraint:
ALTER TABLE dbo.Tablename ADD CONSTRAINT
DF_Tablename_DateColumn DEFAULT(GETDATE()) FOR DateColumn;
-- now add the NOT NULL constraint:
ALTER TABLE dbo.Tablename ALTER COLUMN DateColumn
DATETIME NOT NULL;
-- now you can update the trigger so that it only fires on update:
ALTER TRIGGER dbo.trUpdate
ON dbo.Tablename
FOR UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE Tablename
SET Datecolumn = GETDATE()
WHERE ID IN (SELECT id FROM inserted);
END
GO