上次Row更新了

时间:2012-05-16 13:48:09

标签: sql sql-server triggers

使用日期列更新或插入行的最后一次记录是什么?

我尝试了这个,但它不起作用:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

你应该改变

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

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

因为插入的表可能会带来多个enty。否则它应该可以正常工作。