سؤال

Need help as how I can trap any errors related to executing a sql script in a stored procedure.

select sopScript 
from M_SopInsert 
where soptype = @soptype and sopnumbe = @sopnumbe and lnitmseq = @lnitmseq

If result_count > 0 //if result from above sql query is >0

exec sopScript //loop through the record set and execute sopscript for every record.

Note: sopscript here contains scripts like :

update customerMaster 
set custname='abc' 
where custid=100`"
هل كانت مفيدة؟

المحلول 2

Misread the question originally.

try using

declare @sopScript varchar(1000)

select sopScript 
into #ControlTbl
from M_SopInsert 
where soptype = @soptype and sopnumbe = @sopnumbe and lnitmseq = @lnitmseq


while exists (select * from #ControlTbl)
begin

    select top 1 @sopScript = sopScript
    from #ControlTbl

    begin try
        exec executesql @sopScript = sopScript 
    end try
    begin catch
        *do something*
    end catch

    delete from #ControlTbl
    where sopScript = @sopScript

end

نصائح أخرى

This is how we do it:

Wrap the procedure steps in a TRY and TRANSACTION. Then the individual executions in a TRY

DECLARE @lRollback bit=0
DECLARE @ErrTable TABLE (ErrNumber int,ErrSeverity int,ErrProc varchar(MAX),ErrLine int,ErrMsg varchar(MAX)) --table variable to collect errors.
BEGIN TRY  -- outside begin try
BEGIN TRANSACTION -- wrap transaction
....
   BEGIN TRY
   ...
   END TRY
   BEGIN CATCH
       {ERROR CATCH - see below}
   END CATCH
END TRY
BEGIN CATCH
    SET @lRollback=1
    {ERROR CATCH - see below}       
    ROLLBACK
    BEGIN TRY
        INSERT INTO errorTable (importId,errNumber,errSeverity,errProc,errLine,errMsg) --This is the db default error collection table
        SELECT DISTINCT @importId,ErrNumber,ErrSeverity,ErrProc,ErrLine,ErrMsg FROM @ErrTable
    END TRY
    RETURN -1
END CATCH

Anytime you want to catch an error in the procedure, use this ERROR CATCH:

INSERT INTO @ErrTable (ErrNumber,ErrSeverity,ErrProc,ErrLine,ErrMsg)
SELECT
    ERROR_NUMBER() AS ErrorNumber
    ,ERROR_SEVERITY() AS ErrorSeverity
    ,ERROR_PROCEDURE() AS ErrorProcedure
    ,ERROR_LINE() AS ErrorLine
    ,ERROR_MESSAGE() AS ErrorMessage;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top