Problem:
I have a Scalar Valued Function returning data as VARCHAR(MAX) or NULL (function below), I am using this function to explode a long text string and grab single values (of multiple data types).
I am now trying to insert this data into another table but converted to proper data types but it's failing if the returned value is null.
The field I'm trying to populate is DATETIME NULL so if the function returns null I want to just select null, otherwise I want to convert the VARCHAR to a DATETIME, so far I have:
(SELECT CONVERT(DATETIME, dbo.UDEF_GetFromTextString('Date=', ',', RawData))) AS LineDate,
What I can't do is both handle the null value and convert to a DATETIME, can someone give me a line function to do this (if possible without calling the function twice)?
Error:
Msg 242, Level 16, State 3, Procedure UDEF_DC_TRANSLATE_CALL_DATA, Line 11
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
UDEF_GetFromTextString FUNCTION
CREATE FUNCTION [dbo].[UDEF_GetFromTextString]
-- Input start and end and return value.
(@uniqueprefix VARCHAR(100),
@commonsuffix VARCHAR(100),
@datastring VARCHAR(MAX) )
RETURNS VARCHAR(MAX) -- Picked Value.
AS
BEGIN
DECLARE @ADJLEN INT = LEN(@uniqueprefix)
SET @datastring = @datastring + @commonsuffix
RETURN (
CASE WHEN (CHARINDEX(@uniqueprefix,@datastring) > 0)
AND (CHARINDEX(@uniqueprefix + @commonsuffix,@datastring) = 0)
THEN SUBSTRING(@datastring, PATINDEX('%' + @uniqueprefix + '%',@datastring)+@ADJLEN, CHARINDEX(@commonsuffix,@datastring,PATINDEX('%' + @uniqueprefix + '%',@datastring))- PATINDEX('%' + @uniqueprefix + '%',@datastring)-@ADJLEN) ELSE NULL END
)
END
Edit:
After the very useful help from AakashM, I have located the line and value causing the error, it was trying to pass dd-mm-yyyy as mm-dd-yyyy, working until a value for the day was over 12.
To resolve it I just changed:
(SELECT CONVERT(DATETIME, UDEF_GetFromTextString('Date=', ',', RawData))) AS CallDate
To:
(SELECT CONVERT(DATETIME, UDEF_GetFromTextString('Date=', ',', RawData), 105)) AS CallDate