在MS SQL中连接2个日期

时间:2015-10-18 20:47:39

标签: sql sql-server

我想在下面连接两个日期,但我收到错误

Msg 402, Level 16, State 1, Line 3
The data types date and varchar are incompatible in the add operator.

我的代码是:

SELECT  DATEADD(DAY, -7 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)) [WeekStart],
    DATEADD(DAY, -1 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)) [WeekEnd],
    (DATEADD(DAY, -7 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)) + ' to ' +  DATEADD(DAY, -1 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE))) as Week

预期结果:

WeekStart   WeekEnd      WeekRange
2015-09-27  2015-10-03   2015-09-27 to 2015-10-03

解决

[已解决]使用转换:

SELECT  DATEADD(DAY, -7 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)) [WeekStart],
    DATEADD(DAY, -1 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)) [WeekEnd],
    convert(varchar(10),DATEADD(DAY, -7 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)),110) + ' TO ' +  convert(varchar(10),DATEADD(DAY, -1 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)),110) as Week

2 个答案:

答案 0 :(得分:0)

只需使用convert()与121:

select (left(convert(varchar(255), WeekStart, 121), 10) + ' - ' +
        left(convert(varchar(255), WeekEnd, 121), 10)
       ) as WeekRange

答案 1 :(得分:0)

SELECT DATEADD(DAY, -7 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)) [WeekStart]
      ,DATEADD(DAY, -1 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)) [WeekEnd]
      ,(CONVERT(VARCHAR(10), DATEADD(DAY, -7 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)), 121) 
         + ' to ' 
       +  CONVERT(VARCHAR(10), DATEADD(DAY, -1 - DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE)), 121)) as Week

您无法在列中连接两个日期值,您需要将它们转换为字符串,然后将它们连接成两个值。