Throw exception from SQL Server function to stored procedure -


i have stored procedure in sql server 2012 spxample , scaler-valued function fxample. call function fxample spxample. can throw exception in function , catch in stored procedure's catch block , rethrow calling c# code?

update:

the function wrote like:

create function dbo.fxample(@i int) returns tinyint begin   return (select case when @i < 10      throw 51000,'xample exception',1;     else (select @i)      end); end go 

i getting error

msg 443, level 16, state 14, procedure fxample, line 46 invalid use of side-effecting operator 'throw' within function.

how write alternative code achieve above functionality?

you can forcing error condition when validation fails, provided isn't possible error might occur naturally. when know error can occur when validation has failed, can handle in custom way checking error_number in catch block. example in tempdb:

use tempdb; go  create function dbo.fxample(@i int) returns tinyint begin   return (select case when @i < 10 -- change "validation failed" condition     1/0         -- generate error     else (select @i) -- (you'd have actual retrieval code here)     end); end go  create procedure dbo.spxample   @i int begin   set nocount on;   begin try     select dbo.fxample(@i);   end try   begin catch     if error_number() = 8134 -- divide 0     begin       throw 50001, 'your custom error message.', 1;       -- can throw number > 50000 here     end     else -- else went wrong     begin       throw; -- throw original error     end   end catch end go 

now try out:

exec dbo.spxample @i = 10;  -- works fine exec dbo.spxample @i = 6;   -- fails validation exec dbo.spxample @i = 256; -- passes validation overflows return 

results:

---- 10 

msg 50001, level 16, state 1, procedure spxample, line 12
custom error message.

msg 220, level 16, state 2, procedure spxample, line 7
arithmetic overflow error data type tinyint, value = 256.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -