2016-09-25 64 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

因此,这是两个简单的陈述,这是更新或插入,为更新以更快地达到该记录,您可以添加适当的索引,检查记录的执行计划和数量,然后确定 –