0

我正在尝试访问日期时间列,以查明日期是从今天开始的一周内,还是过期。然后写一个新列的值说Incoming,OverdueFine

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

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

消息 156,级别 15,状态 1,第 3 行
关键字“BETWEEN”附近的语法不正确。

4

5 回答 5

5

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

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
于 2013-05-13T12:27:54.430 回答
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
于 2013-05-13T12:29:04.090 回答
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
于 2013-05-13T12:30:18.260 回答
1

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

于 2013-05-13T12:27:17.110 回答
0

您应该使用 case 语句的其他形式

    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

于 2013-05-13T12:30:12.283 回答