-2

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

请指教

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
4

2 回答 2

0

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

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

从你的代码中删除所有似乎没有任何用处的东西会让你得到这个。

select cast(cast(year(getdate()) as char(4))+'0301' as datetime)
于 2013-09-12T11:03:44.907 回答
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
于 2013-09-12T10:38:20.677 回答