Sql 设置日期时间变量

Sql 设置日期时间变量,sql,datetime,printing,Sql,Datetime,Printing,在SQL中,我执行以下代码。当打印部分运行时,返回“2050年12月31日11:59下午”。我在未显示的代码的后面部分中使用了该变量,它不起作用,并且在将字符串转换为smalldatetime数据类型错误时,转换失败 我是否混淆了格式?我以为datetime是“yyyy-mm-dd hh:mm:ss”,但显然我错了。我看到datetim格式的每个地方都说这应该有效,所以我不知道我做错了什么 declare @date int --@date is yyyymm format

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

我是否混淆了格式?我以为datetime是“yyyy-mm-dd hh: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) 
如果这是Sql Server 试一试

如果需要其他格式的日期,请选中此链接

生成转换错误的代码是什么?我看不出这段代码有什么问题-它应该做什么。是的,这应该可以工作,你能在抛出错误的地方发布代码吗?我执行了此操作,没有收到任何错误-选择1 WHERE@maxEndDate>GETDATE,选择1 WHERECAST@maxEndDate作为smalldatetime>GETDATEyou无法执行此操作-选择1,其中“2050-12-31 23:59:00”*10000>GETDATE将varchar日期字符串乘以10000@seanW很抱歉,我更新了原来的帖子。仅供参考,我之所以将代码设置为字符串,是因为我正在使用存储过程更新视图,这是使其工作的唯一方法。因为字符串有记号和加号的问题,本来很容易的事情变成了一场迂回的噩梦这部分代码-然后用“++@maxEndDate+”替换为“++@maxEndDate+”,当我打印@maxEndDate时,我仍然得到2050年12月31日11:59PM“显示您使用maxEndDate的位置并给出一个错误。问题不在于格式,因为这只是sql显示日期的方式。数据类型存在一些问题,是否缺少强制类型转换或其他内容?当你收到错误的时候给我们看看问题我很抱歉,我更新了原来的帖子。仅供参考,我之所以将代码设置为字符串,是因为我正在使用存储过程更新视图,这是使其工作的唯一方法。因为字符串有记号和加号的问题,本来很容易的事情变成了一个迂回的噩梦。
set @maxEndDate = Convert(smalldatetime, '2050-12-31 23:59', 101)