Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Catching" Errors from within a user defined function in SQL Server 2005

I have a function that takes a number as an input and converts it to a date. This number isn't any standard form of date number, so I have to manually subdivide portions of the number to various date parts, cast the date parts to varchar strings and then, concatenate and cast the strings to a new datetime object.

My question is how can I catch a casting failure and return a null or low-range value from my function? I would prefer for my function to "passively" fail, returning a default value, instead of returning a fail code to my stored procedure. TRY/CATCH statements apparently don't work form within functions (unless there is some type of definition flag that I am unaware of) and trying the standard '@@Error <> 0' method doesn't work either.

like image 999
RLH Avatar asked Nov 25 '25 20:11

RLH


2 Answers

Incidentally this sounds like it could be a scalar UDF. This is a performance disaster, as Alex's blog points out. http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/05/23/reuse-your-code-with-cross-apply.aspx

like image 119
Mark Sowul Avatar answered Nov 28 '25 15:11

Mark Sowul


SELECT CASE WHEN ISDATE(@yourParameter) = 1
   THEN CAST(@yourParameter AS DATETIME) 
   ELSE YourDefaultValue 
END
like image 27
A-K Avatar answered Nov 28 '25 16:11

A-K