2010-02-18 133 views
0

你們看到我處理以下存儲過程中的錯誤的方式有任何問題嗎?如果我做錯了任何事情,我仍然對SQL不夠了解。謝謝:)SQL事務錯誤處理

CREATE PROCEDURE [dbo].[UserAccounts_Create] 
    @username varchar(255), 
    @email varchar(255), 
    @password nvarchar(127), 
    @id bigint OUTPUT 
AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 
    SET XACT_ABORT ON; 

    DECLARE @now smalldatetime 
    SET @now = GETDATE() 

    DECLARE @userId bigint 
    DECLARE @transactionSuccess bit 
    SET @transactionSuccess = 0 

    BEGIN TRANSACTION  
     INSERT INTO UserAccounts([username], [email], [password], [createDate], [lastLoginDate]) 
      VALUES (@username, @email, @password, @now, @now) 

     SET @userId = SCOPE_IDENTITY() 

     INSERT INTO Users([id], [firstName], [lastName]) 
      VALUES (@userId, '', '') 

     SET @transactionSuccess = 1; 

    COMMIT TRANSACTION 

    IF (@transactionSuccess = 1) 
     RETURN 0; -- Success. 
    ELSE 
     RETURN 1; -- Some unknown error occured. 
END 
+0

使用try-catch塊 – Adeel 2010-02-18 05:31:29

回答

3

如果您遇到導致您中止的錯誤,RETURN 1;將永遠不會發生。

而不是使用語法,爲什麼不嘗試一下新的(ISH)

BEGIN TRY 
... 
END TRY 
BEGIN CATCH 
... 
END CATCH 

語法?它給你更多的控制權,並且(IMO)更易於閱讀。

1

我會建議你看看TRY...CATCH (Transact-SQL)

使用這個你可以BEGIN TRANSACTIONCOMMIT TRANSACTION,或ROLLBACK在一個錯誤的事件。