2016-09-25 98 views
0

我正在寫一個存儲過程,它將用於每4分鐘同步一次。這只是一個測試用例,我也需要捕獲異常。有沒有其他方法可以在這個過程中使用try和catch塊,或者這很好嗎?提高SQL Server中的過程性能

這裏是存儲過程:

Create procedure inbound_test 
    @APP1_NO int, 
    @APP1_NAME nvarchar (20), 
    @APP1_CREATED date, 
    @APP1_NO_PK nvarchar(20) 
as 
    if exists (select App1_no from test_in1 where App1_no = @APP1_NO) 
    Begin try 
    Begin transaction 
     Update test_in1 
     set APP1_NO = @APP1_NO, 
      APP1_NAME = @APP1_NAME, 
      APP1_CREATED = @APP1_CREATED, 
      APP1_NO_PK = @APP1_NO_PK 
     where App1_no = @APP1_NO 

    Commit transaction 
    End try 
    Begin Catch 
     If @@Trancount > 0 
      Throw; 
    End Catch 

else 

If @@ROWCOUNT=0 
Begin try 
Begin Transaction 

insert into test_in1(
APP1_NO , 
APP1_NAME , 
APP1_CREATED, 
APP1_NO_PK 
) 
values (@APP1_NO ,@APP1_NAME , @APP1_CREATED,@APP1_NO_PK) 
Commit transaction 
End try 

Begin Catch 
If @@Trancount >0 
Throw; 
End Catch 
GO 

回答

0

單UPDATE或INSERT語句將在原子事務自動地。您不需要顯式事務來啓動和提交。如果該聲明成功,那麼它將被承諾,否則它已經被回滾。你也沒有明確的回滾捕捉,這是沒有必要的。

另外塊不需要另一個條件'IF @@ Rowcount> 0'的原因是,如果它來到其他塊,它意味着你有該值的記錄。

+0

感謝您的迴應卡南。如果我沒有使用else語句,那麼Insert語句無法正常工作。我將從此過程中移除事務。你能告訴我還有什麼我可以做的,以提高性能,因爲這個過程將被一個web服務使用,它將用於每4分鐘同步 – paemmi

+0

因此,這是兩個簡單的陳述,這是更新或插入,爲更新以更快地達到該記錄,您可以添加適當的索引,檢查記錄的執行計劃和數量,然後確定 –