sql trigger在更新时执行更新

时间:2012-01-04 08:46:33

标签: sql triggers

我正在尝试编写一个sql触发器,只要执行更新,它就会更新另一个表。这实际上用于替换复制(复制存在于我们的生产环境中,但不存在于开发环境中,因为它会导致开发问题)。 我写了以下触发器来实现这一点,但它似乎没有用,我不知道为什么。 (我也不知道如何调试触发器)

USE [AuditQuestionnaireManagerDemo]
GO
/****** Object:  Trigger [dbo].[CatchUpdateUser]    Script Date: 01/04/2012 09:25:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER TRIGGER [dbo].[CatchUpdateUser]
   ON  [dbo].[User]
   FOR UPDATE
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    update SharedServicesDemo.dbo.[User]
        set SharedServicesDemo.dbo.[User].Username = Username,
            SharedServicesDemo.dbo.[User].PasswordHash = PasswordHash,
            SharedServicesDemo.dbo.[User].Salt = Salt,
            SharedServicesDemo.dbo.[User].PersonGUID = PersonGUID,
            SharedServicesDemo.dbo.[User].OrganizationGUID = OrganizationGUID,
            SharedServicesDemo.dbo.[User].IsDeleted = IsDeleted,
            SharedServicesDemo.dbo.[User].IsActive = IsActive
        where SharedServicesDemo.dbo.[User].GUID = GUID
    SELECT GUID, ID, Username, PasswordHash, Salt, PersonGuid, OrganizationGUID, IsDeleted, IsActive From Inserted

END

如果有人能在这里发现问题会很棒!

此插入触发器适用于插入/选择组合:

SET IDENTITY_INSERT SharedServicesDemo.dbo.[User] ON
INSERT INTO SharedServicesDemo.dbo.[User] (GUID, ID, Username, PasswordHash, Salt, PersonGUID, OrganizationGUID, IsDeleted, IsActive)
SELECT GUID, ID, Username, PasswordHash, Salt, PersonGuid, OrganizationGUID, IsDeleted, IsActive From Inserted
SET IDENTITY_INSERT SharedServicesDemo.dbo.[User] OFF

1 个答案:

答案 0 :(得分:2)

你的触发器目前什么都不做(你很幸运(不幸?)因为语法编译但没有按你的意愿行事)。尝试:

update SharedServicesDemo.dbo.[User] 
set  SharedServicesDemo.dbo.[User].Username = i.Username,
    SharedServicesDemo.dbo.[User].PasswordHash = i.PasswordHash,
    SharedServicesDemo.dbo.[User].Salt = i.Salt,
    SharedServicesDemo.dbo.[User].PersonGUID = i.PersonGUID,
    SharedServicesDemo.dbo.[User].OrganizationGUID = i.OrganizationGUID,
    SharedServicesDemo.dbo.[User].IsDeleted = i.IsDeleted,
    SharedServicesDemo.dbo.[User].IsActive = i.IsActive
From  SharedServicesDemo.dbo.[User]
inner join inserted i ON SharedServicesDemo.dbo.[User].GUID = i.GUID

参考:UPDATE

[可能需要为SharedServicesDemo.dbo.[User] ...]

的第二个实例添加别名