Home > Mobile >  Error converting varchar to Datetime in a SQL Function
Error converting varchar to Datetime in a SQL Function

Time:04-05

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.

CodePudding user response:

Sample:

Create function [dbo].[getDateValue1](@input_date datetime2)  
returns varchar(100)  
begin  
    declare 
    @v_ret varchar(100)

    set @v_ret = CONVERT(varchar, @input_date, 112)
    return @v_ret
end 


SELECT dbo.getDateValue1('2022-01-01 18:15:15.600')
-- Result: 
20220101
  • Related