I have a user defined function that looks like this;
ALTER FUNCTION [dbo].[func_format_date]
(
-- Add the parameters for the function here
@input VARCHAR(6)
)
RETURNS VARCHAR(6)
AS
BEGIN
-- Declare the return variable here
DECLARE @mon CHAR(2),
@day char(2),
@year char(4),
@output DATETIME
-- Return the result of the function
SELECT @mon = LEFT(@input, 2), @day =SUBSTRING(@input, 3,2), @year = RIGHT(@input,4)
SELECT @output = @year+@mon+@day
RETURN CONVERT(VARCHAR(6), @output, 12)
END
The goal is to be able to pass in a date say “022019” (mmddyy) and the function will format the date as such “190220” (yymmdd). This seems to work only sometime as if I pass in the following dates see the results below; it seems to be inconsistent in terms of the dates it accepts vs the dates that throw an error
022019(Works fine)032019(Works fine)021019(Results in a “The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.” error)030519(Results in a “The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.” error)
I have checked to ensure the default language is correct and it is. Can someone help me to figure this out?
mmddyyoryymmdddate, they are just dates. What's the point of this function? Why not just usesPARSEto parse whatever format is there into a date?