如何在SQL Server触发器中更新行ID

时间:2013-03-25 09:00:48

标签: sql-server sql-server-2008

我有一张表Employee

  Emp_Id  Name
  1       XYZ
  2       ABC

和另一个表DivisionInfo

  DivisionID  Division  Emp_Id
       1       mmm          1
       2       nnnn         1
       3       oooo         1

如果Employee表中存在Emp_Id,我需要编写一个触发器来回滚DivisionInfo表的更新。在这种情况下Emp_Id = 1

如何在SQL触发器中获取正在更新的行的行ID?

这是我的触发码:

ALTER TRIGGER [dbo].[EmployeeTrigger]
ON [dbo].[Employee]
FOR UPDATE 
AS
   IF((SELECT COUNT([DivisionID ]) 
       FROM [DivisionInfo] AS D 
       INNER JOIN Employee AS E ON D.[Emp_Id] = E.Emp_Id
       WHERE D.[Emp_Id] = E.Emp_Id) > 0)
   BEGIN
      RAISERROR ('Testing', 10, 1); 
      ROLLBACK TRANSACTION
      RETURN
   END

这里总是如此

1 个答案:

答案 0 :(得分:1)

试试这个:

ALTER TRIGGER [dbo].[EmployeeTrigger]
ON [dbo].[Employee]
FOR UPDATE 
AS
IF((
    SELECT COUNT([DivisionID ])
    FROM [DivisionInfo] D
    JOIN INSERTED I ON I.[Emp_Id] = D.[Emp_Id])>0)
BEGIN
        RAISERROR ('Testing', 10, 1); 
     ROLLBACK TRANSACTION
     RETURN
END