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

前端 未结 5 774

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:01

    First off - why don't you just return the new ticket number instead of 0 all the time? Any particular reason for that?

    Secondly, to be absolutely sure, you should wrap your INSERT and SELECT statement into a TRANSACTION so that nothing from the outside can intervene.

    Thirdly, with SQL Server 2005 and up, I'd wrap my statements into a TRY....CATCH block and roll back the transaction if it fails.

    Next, I would try to avoid specifying the database server (TestDB42) in my procedures whenever possible - what if you want to deploy that proc to a new server (TestDB43) ??

    And lastly, I'd never use a SET NOCOUNT in a stored procedure - it can cause the caller to erroneously think the stored proc failed (see my comment to gbn below - this is a potential problem if you're using ADO.NET SqlDataAdapter objects only; see the MSDN docs on how to modify ADO.NET data with SqlDataAdapter for more explanations).

    So my suggestion for your stored proc would be:

    CREATE PROCEDURE [dbo].[usp_NewTicketNumber]
    AS
    BEGIN
      DECLARE @NewID INT
    
      BEGIN TRANSACTION
      BEGIN TRY
        INSERT INTO 
          [dbo].[TicketNumber]([CreatedDateTime], [CreatedBy])
        VALUES
          (GETDATE(), SUSER_SNAME())
    
        SET @NewID = SCOPE_IDENTITY()
    
        COMMIT TRANSACTION
      END TRY
      BEGIN CATCH
        ROLLBACK TRANSACTION
        SET @NewID = -1
      END CATCH
    
      RETURN @NewID
    END
    

    Marc

提交回复
热议问题