MSSQL 2008触发器 - 其中variable =两个表之间的公共值

时间:2017-11-13 15:12:05

标签: sql-server-2008 triggers

Triggers的新手,我创建了一个在我硬编码实际需要列为变量的值时有效的。如在代码中,表tbl_measure_stats具有触发器StatsTrigger。当tbl_measure_stats改变时,它设置tbl_activity.override = 0 WHERE tbl_activity.activityid应该等于tbl_measure_status.actid。触发器表中的值是tbl_measures_stats.actid,它应该等于tbl_activity.activityid的id,其值覆盖我需要设置为0.如何编码与54321相关的变量?代码实际上比我的解释简单:

USE [TestDB]
GO
/****** OBJECT: Trigger [dbo].[StatsTrigger]  ******/
/****** PURPOSE: detect any field changes in tbl_measure_stats ******/
/****** ... then set tbl_activity.override = 0 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER TRIGGER [dbo].[StatsTrigger] --resides in tbl_measure_stats>Triggers
ON  tbl_measure_stats --table which has the trigger
AFTER INSERT,DELETE,UPDATE --when something changes...
AS UPDATE tbl_activity set override = 0 where tbl_activity.activityid = 54321

似乎这应该是一个直接的解决方案,但我发现在我的所有搜索中没有任何可操作的。老,新,插入例如...我没有让那些工作。尝试"插入":

时的示例
AS UPDATE cpy_activity set porc = 0 where cpy_activity.activityid = inserted.actid

返回错误:

The multi-part identifier "inserted.actid" could not be bound.

想法?

1 个答案:

答案 0 :(得分:1)

您可能需要在查询的INSERTED子句中包含FROM

ALTER TRIGGER [dbo].[StatsTrigger] --resides in tbl_measure_stats>Triggers
ON  tbl_measure_stats --table which has the trigger
AFTER INSERT,DELETE,UPDATE --when something changes...
AS
  UPDATE A SET override = 0 
  FROM tbl_Activity A JOIN INSERTED I ON A.activityID = I.actid

但请注意,由于INSERTED操作,触发器触发时DELETE不会有任何行。您应该检查INSERTEDDELETED是否有行并相应地做正确的事情。