1

I am creating a UDF in SQL Server. I can not use try-catch block in a user defined function. How can I handle an exception or error in UDF?

CREATE FUNCTION GET_POLICY_NO
(@POLICYID nvarchar(15))
 RETURNS varchar(30)
 AS
 BEGIN
 declare @Return varchar(30)
 select @return = (SELECT POLICY_NO FROM tblPolicy WHERE POLICY_ID = @POLICYID)
return @return
 end

Although tblPolicy is Not exist, it will through error. How can I handle like SP?

5
  • better to paste your code here, cannot help without looking into your code... and why cannot you use try and catch block? Commented Apr 20, 2017 at 12:27
  • @long Added Code in Question. Commented Apr 20, 2017 at 12:44
  • can you take a try with my answer Commented Apr 20, 2017 at 12:51
  • What's the point creating a function which will always fail? Commented Apr 20, 2017 at 13:24
  • the above code is just for example. it's not my requirement. actually this question was asked in an Interview. "How can I handle errors. in Udf" Commented Apr 20, 2017 at 14:00

1 Answer 1

2

You should check This for some answers

And also I have some suggestions:

  1. Since you cant print or use try catch blocks inside a function , use a stored procedure instead, although I dont think you can catch the "Invalid object name 'tblPolicy' " error. I suggest checking if the table exists and then perform your query.

Hope it helps.

Sign up to request clarification or add additional context in comments.

2 Comments

the above code is just for example. it's not my requirement. actually this question was asked in an Interview. "How can I handle errors. in Udf"
@SurajKMad I understand, but it was a little misleading and also there is a lot of info regarding this topic that I`m sure you could've found before asking the question! Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.