更新SQL后触发

时间:2014-02-12 15:27:28

标签: sql sql-server database triggers

我有Customer表。为简化起见,我说我有两列

Id  
Name

我有第二个表(Log),我只想在客户的Id列更改时更新。是的,你听我说主键(Id)会改变!

我采取了刺,但被拉出的NewIdCustomer表中的第一条记录而不是更新的记录

 ALTER TRIGGER [dbo].[tr_ID_Modified]
    ON [dbo].[customer]
 AFTER UPDATE
 AS
 BEGIN
   SET NOCOUNT ON;
   IF UPDATE (Id) 
     BEGIN
        UPDATE [log]
        SET NewId = Id
        FROM customer
     END
  END

1 个答案:

答案 0 :(得分:1)

许多人会认为,如果要更改PK值,则需要重新考虑数据库/表设计。但是,如果你需要一个快速的&脏修复,向customer表添加一个唯一的列(而不是null)。使用此列可以在更新触发器中的[inserted]和[deleted]表之间进行连接。这是一个示例脚本:

CREATE TABLE dbo.Customer (
    Id INT CONSTRAINT PK_Customer PRIMARY KEY,
    Name VARCHAR(128),
    UQColumn INT IDENTITY NOT NULL CONSTRAINT UQ_Customer_UQColumn UNIQUE
)

CREATE TABLE dbo.[Log] (
    CustomerId INT NOT NULL,
    LogMsg VARCHAR(MAX)
)

INSERT INTO dbo.Customer
    (Id, Name)
VALUES
    (1, 'Larry'),
    (2, 'Curley'),
    (3, 'Moe')

INSERT INTO dbo.[Log]
    (CustomerId, LogMsg)
VALUES
    (1, 'Larry is cool'),
    (1, 'Larry rocks'),
    (2, 'Curley cracks me up'),
    (3, 'Moe is mean')


CREATE TRIGGER [dbo].[tr_Customer_Upd]
ON [dbo].[customer]
FOR UPDATE
AS
BEGIN

UPDATE l
SET CustomerId = i.Id
FROM inserted i
JOIN deleted d
    ON i.UQColumn = d.UQColumn
JOIN [Log] l
    ON l.CustomerId = d.Id
END

SELECT *
FROM dbo.[Log]

UPDATE dbo.Customer
SET Id = 4 
WHERE Id = 1

SELECT *
FROM dbo.[Log]