SQL Server 2005中的@@ ERROR

时间:2011-06-06 15:25:22

标签: sql-server-2005

我已经学会使用SCOPE_IDENTITY()而不是@@IDENTITY来获取在给定范围中插入的最后一个标识值,这在高并发方案中非常有用。 @@ ERROR变量是否与该函数等效?我的意思是,有什么方法可以确保每当我写

IF (@@ERROR <> 0) RETURN

我实际上强制函数返回,因为此范围中的最后一个命令导致错误?

2 个答案:

答案 0 :(得分:6)

来自联机丛书:

  

@@ ERROR仅返回错误信息   在Transact-SQL之后立即执行   生成错误的语句。

@@错误仅在当前范围内。所以它应该具有将proc发送到catch块的任何值,无论哪个语句都是错误的。

答案 1 :(得分:5)

在每个语句之后写IF (@@ERROR <> 0)只是不起作用。它需要太多纪律。你应该转到BEGIN TRY/BEGIN CATCHException handling and nested transactions显示了一种T-SQL过程模式,它处理异常和嵌套事务(为了使您的T-SQL代码健壮,需要考虑的事项):

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
        return;
    end catch   
end

另请参阅Error Handling in SQL 2005 and Later以深入讨论整个主题。