-2

I tried the below sample Function ... and i tried in many other ways but still i am getting the Error as "Conversion failed when converting Datetime from character string".. All i am trying is from this function i am returning a Datetime but somewhere here its still string ...

Please advise

declare  @V_Year nvarchar (4), @Test datetime , @t1 as datetime  , @t2 as datetime 
declare @Mon varchar(5) , @dayz varchar (5) , @GMTStart varchar(20)
set @Mon = '03' 
set @t1  = cast ( @Mon as datetime)
set @dayz = '01'
set @t2  = cast ( @dayz as datetime)
SELECT @V_Year =  DATEPART(year, getdate())
set @GMTStart  = @Mon + '-' + @dayz + '-' + convert(nvarchar,@V_Year)
set @Test = Cast(@GMTStart as datetime)
select @Test
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
  • possible duplicate of [Convert varchar into datetime in SQL Server](http://stackoverflow.com/questions/1509977/convert-varchar-into-datetime-in-sql-server) – athabaska Sep 12 '13 at 10:30

2 Answers2

0

I've changed your code a bit:

declare  
    @V_Year nvarchar (4), 
    @Test datetime , 
    @t1 as datetime , 
    @t2 as datetime 
declare 
    @Mon varchar(8), --here need to be varchar(8) because datetime has 8 digits
    @dayz varchar(5), 
    @GMTStart varchar(20)
set @Mon = '20130101' --here you must provide full date, not a part, because is not possible to convert just part of date into full date
set @t1  = cast (@Mon as datetime) --this will work with 
--set @dayz = '01'
--set @t2  = cast (@dayz as datetime) --this line not work with just day, must provide full date

SET @V_Year =  DATEPART(year, getdate()) --here first set a variable, and then select
SELECT @V_Year
set @GMTStart  = @Mon + '-' + @dayz + '-' + convert(nvarchar, @V_Year)
set @Test = Cast(@GMTStart as datetime)
select @Test
veljasije
  • 6,722
  • 12
  • 48
  • 79
0

Your code is creating a datetime value of March 3 in the current year.

The interpretation of date strings is dependent on set dateformat unless you use the format yyyymmdd.

Removing all the stuff from your code that does not seem to do anything useful will leave you with this.

select cast(cast(year(getdate()) as char(4))+'0301' as datetime)
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281