日期:2014-05-17  浏览次数:20670 次

关于SQL SERVER2005 中存储过程中异常的问题
小弟的存储过程中有这样一段代码:
  1 update student set parent_id=@case_id where type='box' and label =@label1;
  2 update student set parent_id=@case_id where type='box' and label =@label2;
  3 update student set parent_id=@case_id where type='box' and label =@label3;
  4 update student set parent_id=@case_id where type='box' and label =@label4;
  5 update student set parent_id=@case_id where type='box' and label =@label5;
  6 update student set parent_id=@case_id where type='box' and label =@label6
其中case_id label1 label2 label3 label4 label5 label6 为传进来的参数 而且 label2 label3 label4 label5 label6有可能传进来是空值
现在的问题是实际执行过程偶尔会出现只有1 2 3行被执行了 4 5 6 没有被执行(1-6传进的值全部不为空),怎么样写代码判断当1-6传进来的值不为空时 6行语句都执行了呢?当1-6都不为空时用try catch能不能捕获没有执行的异常呢?

------解决方案--------------------
SQL code
IF @label2+ @label3 +@label4 +@label5 +@label6 IS NULL 
BEGIN
RETURN 
END 

BEGIN TRY  
update student set parent_id=@case_id where type='box' and label =@label1;
update student set parent_id=@case_id where type='box' and label =@label2;
update student set parent_id=@case_id where type='box' and label =@label3;
update student set parent_id=@case_id where type='box' and label =@label4;
update student set parent_id=@case_id where type='box' and label =@label5;
update student set parent_id=@case_id where type='box' and label =@label6
END TRY 
begin CATCH 
SELECT
    ERROR_NUMBER() AS ErrorNumber
    ,ERROR_SEVERITY() AS ErrorSeverity
    ,ERROR_STATE() AS ErrorState
    ,ERROR_PROCEDURE() AS ErrorProcedure
    ,ERROR_LINE() AS ErrorLine
    ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH

------解决方案--------------------
补充下1#的
SQL code

if @label1+@label2+ @label3 +@label4 +@label5 +@label6 is null or len(@label1)=1 
   or len(@label2)=1 or len(@label3)=1 or len(@label4)=1 or len(@label5)=1 or len(@label6)=1 
    return
else
begin try  
    update student set parent_id=@case_id where type='box' and label =@label1;
    update student set parent_id=@case_id where type='box' and label =@label2;
    update student set parent_id=@case_id where type='box' and label =@label3;
    update student set parent_id=@case_id where type='box' and label =@label4;
    update student set parent_id=@case_id where type='box' and label =@label5;
    update student set parent_id=@case_id where type='box' and label =@label6
end try 
begin catch 
    select ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH

------解决方案--------------------
探讨

补充下1#的
SQL code

if @label1+@label2+ @label3 +@label4 +@label5 +@label6 is null or len(@label1)=1
or len(@label2)=1 or len(@label3)=1 or len(@label4)=1 or len(@label5)=1 or len(@label6)=1
……