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

前端 未结 5 763

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条回答
  •  星月不相逢
    2021-02-09 14:11

    CREATE PROCEDURE [dbo].[usp_NewTicketNumber]
        @NewID int OUTPUT
    AS
    BEGIN
        SET NOCOUNT ON;
        BEGIN TRY
            BEGIN TRANSACTION
            INSERT INTO 
                [dbo].[TicketNumber] ([CreatedDateTime], [CreatedBy])
            VALUES
                (GETDATE(), SUSER_SNAME())
    
            SET @NewID = SCOPE_IDENTITY()
    
            COMMIT TRANSACTION;
        END TRY
        BEGIN CATCH
            IF XACT_STATE() <> 0
                ROLLBACK TRANSACTION;
            SET @NewID = NULL;
        END CATCH
    END
    

    I would not use RETURN for meaningful use data: either recordset or output parameter. RETURN would normally be used for error states (like system stored procs do in most cases):

    EXEC @rtn = EXEC dbo.uspFoo
    IF @rtn <> 0
        --do error stuff
    

    You can also use the OUTPUT clause to return a recordset instead.

    This is "thread safe", that is it can be run concurrently.

提交回复
热议问题