设置日期时间变量

时间:2012-06-28 18:39:23

标签: sql datetime printing

在SQL中,我执行以下代码。当打印部分运行时,它返回'Dec 31 2050 11:59 PM'。我在代码的后面部分使用了该变量(未显示)并且它不起作用,我得到“将字符串转换为smalldatetime数据类型时转换失败”错误。

我的格式混淆了吗?我以为日期时间是'yyyy-mm-dd:mm:ss',但显然我一定是错的。我查看datetim格式的每个地方都说这应该有用,所以我不知道我做错了什么。

        declare @date int

--@date is yyyymm format


declare @sql_v_fx as varchar(max), @sql_dim_for_exc as varchar(max)
declare @maxEndDate as smalldatetime

set @date = 201202
set @maxEndDate = Convert(smalldatetime, '2050-12-31 23:59', 101)

print @maxenddate

--remove prior date in [zstbl_fx_rollback]
truncate table zstbl_fx_rollback 

--insert the user entered month
--specify in the VS report whether it's Balance Sheet or Income Statement date
insert into [zstbl_fx_rollback] (yyyymm) select @date

--alter the v_fx view to into account the date in the [zstbl_fx_rollback] table
select @sql_v_fx = 
'
    Alter view [dbo].[v_fx] as
    select 
          [foreign exchange key],[currency key], [to usd], [from usd], [effective date], 
          [expiration date] = 
                case when [effective date] = 
                      convert(datetime,cast((select isnull(max(yyyymm),205012) from zstbl_fx_rollback) * 100 + 1 as char(8))) then ' + @maxEndDate + ' else [expiration date] end
          ,[is current] 
          ,[effective date key] = year([effective date]) * 10000 + month([effective date])*100

    from crs..[dim foreign exchange]
    where [effective date] <= convert(datetime,cast((select isnull(max(yyyymm),205012) from zstbl_fx_rollback) * 100 + 1 as char(8))) 
'

exec(@sql_v_fx) 

1 个答案:

答案 0 :(得分:0)

如果是Sql-Server 试试

set @maxEndDate = Convert(smalldatetime, '2050-12-31 23:59', 101)

如果您需要其他格式的日期,请检查此链接 http://msdn.microsoft.com/es-es/library/ms187928.aspx