具有多行的复杂SQL Server更新触发器

时间:2012-06-12 19:31:08

标签: sql-server tsql sql-server-2008-r2

我在SQL Server 2008 R2下有一个更新触发器的小问题。我已经安装了一个触发器来将更改记录到日志表中。这对我来说很好,但是当我更新多行时却没有。

CREATE TRIGGER [dbo].[TR_CompaniesUpdated]
ON  [dbo].[Companies]
AFTER UPDATE
AS 
BEGIN
SET NOCOUNT ON;
DECLARE
    @Return NVARCHAR(MAX), -- Is the JSON of the data
    @ParameterSQL VARCHAR(MAX), -- Is the select we want to retreive in JSON format

    -- Data from of the row updated
    @ID INT,
    @StatusID SMALLINT,

    -- Old data from of the row
    @StatusID2 SMALLINT

-- Declare the cursor
DECLARE InsertedCursor CURSOR FAST_FORWARD FOR
SELECT [ID], [StatusID] FROM INSERTED

-- Create the temporary table with logs so we'll need to do only one insert after this
CREATE TABLE #tempLog(
    [ID] [int] NOT NULL,
    [Data] [nvarchar](max) NOT NULL,
    [ActionID] [int] NOT NULL,
    [DtCreated] [datetime] NOT NULL,
    [CreatedBy] [int] NOT NULL)

-- Save updated values into variables
OPEN InsertedCursor
FETCH NEXT FROM InsertedCursor
INTO @ID, @StatusID

WHILE @@fetch_status = 0
BEGIN
    -- Save old values into variables
    SELECT
        @StatusID2 = [StatusID]
    FROM DELETED
    WHERE [ID] = @ID

    SELECT * INTO #tempTable
    FROM DELETED
    WHERE [ID] = @ID

    -- Build the select only to et the changed data
    SET @ParameterSQL = 'SELECT '
    IF (ISNULL(@StatusID, '') != ISNULL(@StatusID2, '')) SET @ParameterSQL = @ParameterSQL + '[StatusID],'
    IF (@ParameterSQL != 'SELECT ')
    BEGIN
        -- Update the modified date
        UPDATE [dbo].[AssessedLevelCostCentre]
        SET [DtModified] = GETDATE()
        WHERE [ID] = @ID

        SET @ParameterSQL = SUBSTRING(@ParameterSQL, 0, LEN(@ParameterSQL)) + ' FROM #tempTable'

        -- Execute the JSON function to get the result in JSON format
        EXEC [dbo].[GetJSON] @ParameterSQL, @Return = @Return OUTPUT

        -- Insert the Change Log with the old data
        INSERT INTO #tempLog
        SELECT
            [ID] AS [ID],
            @Return AS [Data],
            [ActionID] AS [ActionID],
            CASE
                WHEN [DtModified] IS NULL
                    THEN [DtCreated]
                    ELSE [DtModified]
            END AS [DtModified],
            CASE
                WHEN [ModifiedBy] IS NULL
                    THEN [CreatedBy]
                    ELSE [ModifiedBy]
            END AS [CreatedBy]
        FROM #tempTable
    END
    ELSE
    BEGIN
        UPDATE [dbo].[AssessedLevelCostCentre]
        SET [ModifiedBy] = (SELECT [ModifiedBy] FROM #tempTable)
        WHERE [ID] = @ID
    END

    DROP TABLE #tempTable

    -- Advance the Cursor
    FETCH NEXT FROM InsertedCursor
    INTO @ID, @StatusID
END

CLOSE InsertedCursor
DEALLOCATE InsertedCursor

-- Insert the Change Log with the old data
INSERT INTO [dbo].[AssessedLevelsCostCentersLogs]
SELECT *
FROM #tempLog

DROP TABLE #tempLog
END

正如您所看到的,我有一个存储过程而不是返回JSON数据,问题是存储过程从查询中获取数据而我无法传递DELETED或INSERTED表,这就是我使用的原因临时表似乎可以解决问题,但添加了ID子句。

已更新

我更新了代码,现在我有一个光标但是我可以看到它的性能非常慢。我将以这种方式需要这个因为我无法更改应用程序来创建JSON,我认为我触发这样就可以正常工作。任何人都有想法或如何提高这个性能?

1 个答案:

答案 0 :(得分:3)

Sql server中的触发器为每个批处理运行一次,因此如果在一个语句中插入5000条记录,则触发器将启动一次。您所做的是假设它将为每个单独的记录运行,方法是设置您想要标量变量的值,当然只能保存一个值而不是5000.您需要重新考虑您的过程以利用加入到插入和删除一次不能通过一条记录。