你的語法只是一個小關:
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
對不起,更多的錯字,感謝一百萬,工作就像abracadabra!,你好! – user851971
第一個觸發器爲我工作,它爲任何插入或更新記錄日期/時間戳記,因爲我在實現您的解決方案之前更改了Table Xture(dateColumn NOT NULL DEFAULT GETDATE())。 – user851971