Sql-Server

SQL 選擇 WHERE 行已更新

  • August 20, 2012
USE [RF_WORLD]
GO
/****** Object:  Trigger [dbo].[lastdeathtrigg]    Script Date: 08/20/2012 10:52:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Mauro Tamm
-- =============================================
ALTER TRIGGER [dbo].[lastdeathtrigg]
  ON  [dbo].[tbl_pvporderview]
  AFTER UPDATE
AS 
IF (UPDATE(Death))
BEGIN
   SET NOCOUNT ON;
DECLARE @userserial int;
SELECT @userserial ='serial' WHERE UPDATE(Death)
Insert INTO [RF_WORLD].[dbo].[lastdeath]
(serial)
VALUES (@userserial)
END

where 部分是可疑的,它會這樣工作嗎?本質上,如果它實際更新,我需要它只選擇行序列值。

觸發器有幾個問題:

  1. 您假設觸發器按行觸發,而觸發器按語句觸發。這意味著您不能只分配一個變數,因為如果更新影響多行,這將不起作用。
  2. 您分配變數的查詢不會從任何地方提取 - 您需要引用inserted和/或deleted偽表。
  3. 檢查UPDATE()只會告訴您該列已被引用,但不會告訴您該值是否已更改。

以下是我將如何重寫您的觸發器:

-- this assumes Death is not nullable

ALTER TRIGGER [dbo].[lastdeathtrigg]
  ON  [dbo].[tbl_pvporderview]
  AFTER UPDATE
AS 
IF (UPDATE(Death))
BEGIN
 SET NOCOUNT ON;

 INSERT RF_WORLD.dbo.lastdeath(serial)
   SELECT i.serial FROM inserted AS i
   INNER JOIN deleted AS d
   ON i.serial = d.serial 
   AND i.Death <> d.Death;
END
GO

引用自:https://dba.stackexchange.com/questions/22785