datetime列上的CASE表达式

时间:2013-05-13 12:25:16

标签: sql sql-server tsql

我试图访问日期时间列,以确定日期是从今天开始的一周内还是过期。然后写一个新列的值来说IncomingOverdueFine

SELECT
CASE next_action_date
WHEN (BETWEEN GETDATE()+7 AND GETDATE()) THEN 'Incoming'
WHEN (< GETDATE()) THEN 'Overdue'
ELSE 'Fine'
END AS condition
FROM
tableName

这是我到目前为止所获得的,但正如你可以看到的那样,它根本不起作用:

  

Msg 156,Level 15,State 1,Line 3
  关键字&#39; BETWEEN&#39;附近的语法不正确。

5 个答案:

答案 0 :(得分:5)

CASE表达式two syntaxes - 所谓的简单,它将单个值与其他值列表进行比较,并且已搜索具有通用布尔条件的一个。您选择了简单的案例,但它没有足够的灵活性来满足您的需求;你应该切换到搜索的语法,如下所示:

SELECT
CASE
    WHEN next_action_date BETWEEN GETDATE() AND GETDATE()+7 THEN 'Incoming'
    WHEN next_action_date < GETDATE() THEN 'Overdue'
    ELSE 'Fine'
END AS condition
FROM
tableName

答案 1 :(得分:4)

请尝试

select CASE 
    when next_action_date between GETDATE() and GETDATE()+7 then 'Incoming'
    when next_action_date < GETDATE() THEN 'Overdue'
    else 'fine' end as Condition
from(
    select GETDATE()+6 next_action_date
)x

答案 2 :(得分:2)

试试这个 -

DECLARE @Date DATETIME
SELECT @Date = GETDATE()

SELECT
    condition = CASE 
        WHEN t.next_action_date BETWEEN @Date AND DATEADD(DAY, 7, @Date) THEN 'Incoming'
        WHEN t.next_action_date < @Date THEN 'Overdue'
        ELSE 'Fine'
    END 
FROM dbo.tableName t

答案 3 :(得分:1)

使用DATEADD(Day, 7, GETDATE())

答案 4 :(得分:0)

您应该使用案例陈述的另一种形式

    SELECT
    CASE 
        WHEN (next_action_date BETWEEN GETDATE()+7 AND GETDATE()) THEN 'Incoming'
        WHEN (next_action_date < GETDATE()) THEN 'Overdue'
        ELSE 'Fine'
    END AS condition
    FROM
    tableName

http://www.devx.com/tips/Tip/15633