2012-05-16 69 views
-1

上次使用日期列更新或插入行時記錄的最佳觸發是什麼?上一次行更新

我想這一點,但它不工作:

CREATE TRIGGER trUpdate ON Tablename FOR INSERT, UPDATE 
AS 

    IF @@nestlevel = 0 
    BEGIN 

    UPDATE Tablename 
     SET Datecolumn = GETDATE() 
     FROM 
    WHERE ID = (SELECT i.id FROM INSERTED i) 

    END 

回答

4

你的語法只是一個小關:

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 
+0

對不起,更多的錯字,感謝一百萬,工作就像abracadabra!,你好! – user851971

+0

第一個觸發器爲我工作,它爲任何插入或更新記錄日期/時間戳記,因爲我在實現您的解決方案之前更改了Table Xture(dateColumn NOT NULL DEFAULT GETDATE())。 – user851971

1

你應該改變

UPDATE Tablename 
     SET Datecolumn = GETDATE() 
    WHERE ID = (SELECT i.id FROM INSERTED i) 

TO

IF NOT UPDATE(Datecolumn) 
UPDATE Tablename 
     SET Datecolumn = GETDATE() 
    WHERE ID IN (SELECT i.id FROM INSERTED i) 

由於插入的表可能conain多個enty。否則它應該工作正常。

+0

語法仍然是錯誤的。你試過了嗎? –

+0

謝謝Mith!爲你的見解。 – user851971

+0

@AaronBertrand:對不起,錯過了懸空,編輯了代碼 – Mithrandir