我正在尝试创建一个触发器,只有在值已更改时才更新列。根据我的阅读,可以通过比较插入和删除的表来完成。以下是我尝试进行比较的方法。
还有其他方法吗?我认为select
查询和if
语句可以在某些方面嵌套,但我无法弄清楚如何。
CREATE TRIGGER [dbo].[tr_Persoane_Update]
ON [dbo].[Persoane]
AFTER UPDATE
AS BEGIN
SET NOCOUNT ON;
DECLARE @DFirstName varchar(30),
@IFirstName varchar(30),
@DLastName varchar(30),
@ILastName varchar(30)
SELECT @DFirstName=D.FirstName, @DLastName=D.LastName
FROM Deleted AS D
SELECT @IFirstName=I.FirstName, @ILastName=I.LastName
FROM Inserted AS I
IF @DFirstName <> @IFirstName
BEGIN
UPDATE FirstName
SET FirstName = @IFirstName
WHERE FirstName = @DFirstName
END
IF @DLastName <> @ILastName
BEGIN
UPDATE LastName
SET LastName = @ILastName
WHERE LastName = @DLastName
END
END
我也试过这种方法,但我没有正确使用CASE语句。
ALTER TRIGGER [dbo].[tr_Persons_Update]
ON [dbo].[Persons]
AFTER UPDATE
AS BEGIN
SET NOCOUNT ON;
SELECT D.FirstName, D.LastName, D.ID_Title, I.FirstName, I.LastName, I.ID_Title,
CASE WHEN D.FirstName <> I.FirstName
THEN
BEGIN
UPDATE Persons
SET FirstName = I.FirstName
WHERE FirstName = D.FirstName
PRINT 'FirstName modified'
END
/*END
CASE*/ WHEN D.LastName <> I.LastName
THEN
BEGIN
UPDATE Persons
SET LastName = I.LastName
WHERE LastName = D.LastName
PRINT 'LastName modified'
END
/*END
CASE*/ WHEN D.ID_Title <> I.ID_Title
THEN
BEGIN
UPDATE Persons
SET ID_Title=I.ID_Title
WHERE ID_Title=D.ID_Title
END
END
FROM DELETED AS D
INNER JOIN INSERTED AS I ON D.ID_Person=I.ID_Person
END
答案 0 :(得分:0)
以下是名字的示例:
update fn
set firstname = id.newfname
from firstname fn join
(select i.firstname as newfname, d.firstname as oldfname
from inserted i join
deleted d
on i.personid = d.personid
where i.firstname <> d.firstname
) id
on fn.firstname = id.oldname;
您不应该假设inserted
和deleted
只包含一个值。这需要与{2}匹配的id
inserted
和deleted
实际上是视图而非表格。