多次插入后插入失败后触发

时间:2019-04-01 14:59:57

标签: sql sql-server triggers sql-update

我有一个插入后被触发的触发器。它触发一个存储过程,该存储过程更新表IsLast中的列CompanyStatus

Id | CompanyId | Status | DateCreated | IsLast

此存储过程应在1列中设置IsLast,以记录最大Id的记录。

CREATE PROCEDURE [dbo].[spCompanyStatusAfterInsert](@schemaName nvarchar(100),  @dataTable CompanyStatus READONLY)
AS
BEGIN
    DECLARE @sql nvarchar(max)

    SELECT @sql = N'DECLARE
        @Id bigint,
        @companyId uniqueidentifier;

        DECLARE CompanyStatus_Cursor CURSOR FAST_FORWARD FOR
        SELECT Id, CompanyId
        FROM @dataTable

        OPEN CompanyStatus_Cursor 

        FETCH NEXT FROM CompanyStatus_Cursor 
        INTO @Id, @companyId

        WHILE @@FETCH_STATUS = 0
        BEGIN
            UPDATE ' + QUOTENAME(@schemaName ) + N'.[CompanyStatus]
            SET IsLast = 0
            WHERE Id IN (SELECT Id
                         FROM ' + QUOTENAME(@schemaName) + N'.[CompanyStatus]
                         WHERE Id <> @Id
                               AND CompanyId = @companyId
                               AND IsLast = 1) 

            UPDATE ' + QUOTENAME(@schemaName) + N'.[CompanyStatus]
            SET IsLast = 1
            WHERE Id = @Id

            FETCH NEXT FROM crs
            INTO @Id, @companyId
        END

        CLOSE CompanyStatus_Cursor 
        DEALLOCATE CompanyStatus_Cursor'

    EXEC sp_executesql @sql, N'@schemaName nvarchar(100), @dataTable CompanyStatus READONLY', @schemaName, @dataTable
END

(首先将所有现有的IsLast更新为0,然后将1设置为最新的Id-这是预期的行为)。

问题-当我在很短的时间内执行2次插入操作时,结果我得到了IsLast = 1的2条记录。

Id | CompanyId                            | Status | DateCreated             | IsLast
19 | 8afbd9cb-02f9-45d7-a605-a54052866bd4 | 1      | 2019-04-01 12:08:59.540 | 1
18 | 8afbd9cb-02f9-45d7-a605-a54052866bd4 | 1      | 2019-04-01 12:10:57.790 | 1
17 | fc7d1f2b-a72a-4d7f-99fa-602c72fb0410 | 2      | 2019-03-30 12:14:57.294 | 1
16 | 8afbd9cb-02f9-45d7-a605-a54052866bd4 | 1      | 2019-03-29 12:10:57.790 | 0

在示例中,具有ID 18的行不应该与IsLast = 1在一起,因为存在具有较大ID的行。


执行此更新查询时是否有问题? (第一次更新在第二次开始之前尚未完成)。


触发代码:

CREATE TRIGGER [{schema}].[{schema}_TRG_CompanyStatus]
ON [{schema}].[CompanyStatus]
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @dataTable CompanyStatus

    INSERT INTO @dataTable SELECT Id, CompanyId  FROM inserted

    EXEC [dbo].[spCompanyStatusAfterInsert] N'{schema}', @dataTable
END

GO

1 个答案:

答案 0 :(得分:0)

测试此

<AppleRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"><RegistrationId i:nil="true" /><DeviceToken>1234</DeviceToken></AppleRegistrationDescription>
<AppleRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"><RegistrationId i:nil="true" /><DeviceToken>4321</DeviceToken></AppleRegistrationDescription>