运行此查询时出错:
SELECT '06/30/' +
CASE WHEN GETDATE() BETWEEN Cast('1/01/' + YEAR(GETDATE()) + ' 12:01:01' As DateTime) And Cast('6/30/' + YEAR(GETDATE()) + ' 12:01:01' as DateTime)
THEN CAST(
YEAR(DATEADD(YY, 2, GETDATE())) AS VARCHAR(4))
WHEN GETDATE() BETWEEN Cast('7/01/' + YEAR(GETDATE()) + ' 12:01:01' As DateTime) And Cast('12/31/' + YEAR(GETDATE()) + ' 12:01:01' as DateTime)
THEN CAST(
YEAR(DATEADD(YY, 3, GETDATE())) AS VARCHAR(4))
END
AS DateEnding FOR XML RAW
Conversion failed when converting the varchar value '1/01/' to data type int.
答案 0 :(得分:2)
在尝试将其与文本组合时,您需要将YEAR(GETDATE())
CAST或CONVERT到varchar(4),否则,它会尝试将文本转换为int。
SELECT '06/30/' +
CASE WHEN GETDATE() BETWEEN Cast('1/01/' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) + ' 12:01:01' As DateTime) And Cast('6/30/' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) + ' 12:01:01' as DateTime)
THEN CAST(
YEAR(DATEADD(YY, 2, GETDATE())) AS VARCHAR(4))
WHEN GETDATE() BETWEEN Cast('7/01/' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) + ' 12:01:01' As DateTime) And Cast('12/31/' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) + ' 12:01:01' as DateTime)
THEN CAST(
YEAR(DATEADD(YY, 3, GETDATE())) AS VARCHAR(4))
END
AS DateEnding FOR XML RAW
答案 1 :(得分:0)
JamieSee将其转换为VARCHAR(4)是正确的。更好的方法是使用非模糊日期进行格式化。 SQL将永远在2012年6月30日的2012年6月30日,但是在7月1日(美国格式)或1月7日(英国格式)的1/7/2012?
SELECT '06/30/' +
CASE WHEN GETDATE() BETWEEN Cast(CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-01-01 12:01:01' As DateTime) And Cast(CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-06-30 12:01:01' as DateTime)
THEN CAST(
YEAR(DATEADD(YY, 2, GETDATE())) AS VARCHAR(4))
WHEN GETDATE() BETWEEN Cast(CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-07-01 12:01:01' As DateTime) And Cast(CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-12-31 12:01:01' as DateTime)
THEN CAST(
YEAR(DATEADD(YY, 3, GETDATE())) AS VARCHAR(4))
END
AS DateEnding FOR XML RAW