I want to create function to use it in creation of view. In my table there are strings (strings are consists only of 8 digits) that I'm converting into DATE.
My function is:
CREATE FUNCTION MY.FUNCTION(@date int)
RETURNS DATE
AS
BEGIN
RETURN CONVERT(DATETIME, @date)
END
If I use smth like SELECT FUNCTION('20170323') FROM TABLE
it works as expected.
But if I'll try smth like SELECT FUNCTION('77777777') FROM TABLE
it fails of course... But if it fail I need to retut NULL!
After some digging I have no result about function modification.
How to add exception handling in my function properly to return date on NULL if it fails?
After a long investigation and lot of efforts I've found my solution:
CREATE FUNCTION MY_FUNCTION(@date CHAR(20))
RETURNS DATE
AS
BEGIN
RETURN
(CASE
WHEN ISDATE(@date) = 0
THEN NULL
ELSE CAST(@date AS DATE)
END)
END
Sybase method ISDATE() doing all magic in this case without throwing exception...