SQL Server - 插入或更新触发器在涉及复制时并不总是触发

时间:2012-05-11 19:14:24

标签: sql-server triggers replication

我们的Microsoft SQL Server数据库中有一个通知系统。会发生什么是由名为NotifyOnPropertyChangedTrigger的SQL触发器创建的文件。我们的客户端软件使用.NET FileSystemWatcher类来等待新文件出现,它会读取并获取新的属性设置。除非涉及SQL复制,否则这很有效。

问题是这样的:

因此我们在主数据库中插入一个更改(复制到其他3个SQL Server数据库)SQL Trigger检测到更改,并在硬盘上正确创建文件。我们的数据库复制正确更新了其他3个DQL DB以反映最新的更改。但是,触发器仅偶尔工作,这意味着并不总是在其他3个硬盘上创建文件。 (它应该是。总共4个文件:1个在主DB上创建,3个在复制DB上创建)

我们正在使用合并复制。

为什么会发生这种情况?

提前致谢。

这是触发器:

ALTER TRIGGER [dbo].[NotifyOnPropertyChangeTrigger] 
   ON [dbo].[PropertyValues] 
   AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
    SET NOCOUNT ON

    DECLARE @propertyValueID int

    DECLARE PropertyValueCursor CURSOR FOR
    SELECT DISTINCT [PropertyValueID]
    FROM (SELECT [PropertyValueID] FROM inserted
          UNION ALL
          SELECT [PropertyValueID] FROM deleted) AS Combined

    OPEN PropertyValueCursor
    FETCH NEXT FROM PropertyValueCursor INTO @propertyValueID

    WHILE @@FETCH_STATUS = 0
    BEGIN
        DECLARE @propertyID int
        DECLARE @profileID int
        DECLARE @contractName nvarchar(255)

        IF ((SELECT COUNT(*) FROM inserted WHERE [PropertyValueID] = @propertyValueID) > 0)
        BEGIN
            SELECT @propertyID = [PropertyID], @profileID = [ProfileID], @contractName = [ContractName]
            FROM inserted
        END
        ELSE
        BEGIN
            SELECT @propertyID = [PropertyID], @profileID = [ProfileID], @contractName = [ContractName]
            FROM deleted
        END

        DECLARE @propertyName nvarchar(255)
        DECLARE @needToSendNotification bit
        SELECT @propertyName = [PropertyName], @needToSendNotification = [NotifyOnUpdate]
        FROM [Properties]
        WHERE [PropertyID] = @propertyID

        IF (@needToSendNotification = 1)
        BEGIN
            DECLARE @profileName nvarchar(50)
            SELECT @profileName = [ProfileName]
            FROM [Profiles]
            WHERE [ProfileID] = @profileID

            DECLARE @fileName nvarchar(600) -- Must be at least 50 + 1 + 255 + 1 + 255 + 19 + 4
            SET @fileName =   dbo.CleanStringForFileName(@profileName)
                            + '-'
                            + dbo.CleanStringForFileName(@contractName)
                            + '-'
                            + dbo.CleanStringForFileName(@propertyName)
                            + '-'
                            + dbo.GetUTCDateTimeStampWithSeparator('-')
                            + '.txt'

            DECLARE @commandString nvarchar(650) -- Must be at least 5 + 10 + 27 + 585
            SET @commandString = 'echo ' + CAST(@propertyValueID AS nvarchar(10)) + ' >> C:\ClientNotifications\' + @fileName

            EXEC master.dbo.xp_cmdshell @commandString, NO_OUTPUT
        END

        FETCH NEXT FROM PropertyValueCursor INTO @propertyValueID
    END

    CLOSE PropertyValueCursor
    DEALLOCATE PropertyValueCursor
END

0 个答案:

没有答案