-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

2 回答 2

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
于 2012-05-16T13:50:55.050 回答
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)

因为插入的表可能包含多个实体。否则它应该可以正常工作。

于 2012-05-16T13:51:17.553 回答