转换失败从字符串转换为datetime

时间:2013-09-12 10:26:10

标签: sql-server sql-server-2005 datetime

我尝试了下面的示例函数...并且我尝试了许多其他方式,但我仍然得到错误为“从字符串转换日期时转换失败”..我正在尝试的是从这个函数我返回一个日期时间,但在这里仍然是一个字符串......

请告知

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

2 个答案:

答案 0 :(得分:0)

我已经改变了你的代码:

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

答案 1 :(得分:0)

您的代码在当前年份创建了3月3日的日期时间值。

日期字符串的解释取决于set dateformat,除非您使用格式yyyymmdd

从您的代码中删除所有似乎没有做任何有用的东西,这将留给您。

select cast(cast(year(getdate()) as char(4))+'0301' as datetime)