2016-10-07 119 views
0

這是我的代碼。如何避免發生錯誤發生任何查詢自動回滾已經存儲。如何在SQL Server存儲過程中執行多次插入錯誤Happend回滾插入表

insert into muser(UserKey, Email, UserPassword) 
values(@Key, @Useremail, 'test') 

set @UserId = SCOPE_IDENTITY() 
set @Key = NEWID() 

insert into mUserProfile(UserProfileKey, UserId, UserEmail) 
values(@Key, @UserId, @Useremail) 

exec SP_Store @Useremail, @ClientId, 
+0

不太明白你在問什麼。你只是在問你把代碼放在一個事務中並回滾?檢查:https://msdn.microsoft.com/en-gb/library/ms188929.aspx – Tanner

+0

備註:你應該**不要**爲存儲過程使用'sp_'前綴。微軟已經保留了這個前綴以供自己使用(參見*命名存儲過程*)](http://msdn.microsoft.com/en-us/library/ms190669%28v=sql.105%29.aspx),以及你將來有可能冒着名字衝突的風險。 [這對你的存儲過程性能也是不利的](http://www.sqlperformance.com/2012/10/t-sql-queries/sp_prefix)。最好只是簡單地避免使用'sp_'並將其他內容用作前綴 - 或者根本沒有前綴! –

回答

0

你的問題不是很清楚,但我想你想要的東西沿着這些線。

begin transaction 

begin try 

    insert into muser(UserKey,Email,UserPassword) 
    values(@Key,@Useremail,'test') 

    set @UserId= SCOPE_IDENTITY() 
    set @Key =NEWID() 


    insert into mUserProfile(UserProfileKey,UserId,UserEmail) 
    values(@Key,@UserId,@Useremail) 

    exec SP_Store @Useremail,@ClientId --You should avoid the SP_ prefix. 

    commit transaction 
end try 
begin catch 
    --Report the error here, do NOT silently rollback you transaction 
    rollback transaction 
end catch 

這應該與一個警告。如果你有一個事務是SP_Store,這將不會正常工作,因爲你不能在sql server中嵌套事務。

此外,你真的避免了SP_前綴,或者甚至更好地避免了前綴。 http://sqlperformance.com/2012/10/t-sql-queries/sp_prefix

相關問題