1

运行此查询时出现错误:

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.

4

2 回答 2

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
于 2012-12-04T23:46:00.837 回答
0

JamieSee 将其转换为 VARCHAR(4) 是正确的。更好的方法是使用明确的日期进行格式化。SQL 将始终将 2012 年 6 月 30 日计算为 2012 年 6 月 30 日,但 2012 年 1 月 7 日是 7 月 1 日(美国格式)还是 1 月 7 日(英国格式)?

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
于 2012-12-04T23:55:03.027 回答