I am trying to create a function that converts a given date string to the desired DateTime format. The code is:
Alter function dbo.getDateValue1(@inputdate varchar)
returns varchar
as
begin
declare @inputDateTransformed datetime = CAST(@inputdate AS datetime2)
declare @setDatevalue varchar = convert(varchar,@inputDateTransformed ,112)
return @setDatevalue
end
And I am calling the function as below:
SELECT dbo.getDateValue1('2022-01-01 18:15:15.600' )
Which gives me the error: Conversion failed when converting date and/or time from character string.
Any help would be appreciated.
VARCHARwithout a length, which is a bad habit to kick. Here it meansVARCHAR(1). Note that using a scalar-valued function for an operation like this is a bad idea prior to SQL Server 2019 (which offers inlining of such functions) as it will tank your performance hard if it's used over multiple rows.CONVERTin the first place? Smells like an XY Problem.CONVERTfunction. As @JeroenMostert warned though, scalar functions can provide poor performance; especially when they can't be inlined (due to your version or because they aren't able to be). Inline table value functions are far often a more performant solution, which is also version agnostic. But the reason for your error, as they also noted, is due to the (omission of the) length property of yourvarchardeclarations; which is several places is therefore avarchar(1).