Is this stored procedure thread-safe? (or whatever the equiv is on SQL Server)

前端 未结 5 759

With the help of others on SO I\'ve knocked up a couple of Tables and Stored Procedures, this morning, as I\'m far from a DB programmer.

Would someone mind casting an ey

5条回答
  •  梦毁少年i
    2021-02-09 14:11

    The safest way to go here would probably be to use the Output clause, since there is a known bug in scope_idendity under certain circumstances ( multi/parallel processing ).

    CREATE PROCEDURE [dbo].[usp_NewTicketNumber]
    AS
    BEGIN
      DECLARE @NewID INT
    
      BEGIN TRANSACTION
      BEGIN TRY
        declare @ttIdTable TABLE (ID INT)
        INSERT INTO 
          [dbo].[TicketNumber]([CreatedDateTime], [CreatedBy])
        output inserted.id into @ttIdTable(ID)
        VALUES
          (GETDATE(), SUSER_SNAME())
    
        SET @NewID = (SELECT id FROM @ttIdTable)
    
        COMMIT TRANSACTION
      END TRY
      BEGIN CATCH
        ROLLBACK TRANSACTION
        SET @NewID = -1
      END CATCH
    
      RETURN @NewID
    END
    

    This way you should be thread safe, since the output clause uses the data that the insert actually inserts, and you won't have problems across scopes or sessions.

提交回复
热议问题