基于日期的SQL Case语句

时间:2012-11-21 12:21:20

标签: sql sql-server-2008 tsql sql-update case

我需要创建一个包含CASE语句的查询,该语句基本上是

CASE if getdate() > datedue by 31 days
    then status = 'Blocked
END

有没有人知道如何检查今天的日期是否大于说,25/10/2012到31天?

修改

Select co.OrderID, cu.FName + '  ' + cu.SName as 'Name', 
cu.Address1 + ', ' + cu.Address2 + ', ' + cu.Address3 as 'Dispatch Address', 
cu.PostCode, 
ma.MaterialName as 'Item',
mi.Price as 'Item Price',
co.DateOrdered as 'Order Date',
pm.DueDate,
pm.Overdue,

HERE I NEED TO WRITE A CASE STATEMENT TO INSERT INTO A LOCKEDACCOUNT TABLE
so for example CASE WHEN DATEDIFF(dd, GETDATE(), pm.DueDate) >= 31 THEN INSERT INTO LOCKEDACCOUNT (id, status, datelocked, customerid) VALUES (.....)
END

from Customers cu

2 个答案:

答案 0 :(得分:6)

像这样:

SELECT 
  CASE 
    WHEN DATEDIFF(dd, GETDATE(), @duedate) >= 1 THEN 'blocked' 
    ELSE 'Not' 
  END AS Status;

SQL Fiddle Demo

请注意:如果您未指定ELSE子句,则默认值为NULL

更新:您可以插入包含CASE表达式的表格,如下所示:

INSERT INTO Statuses VALUES
(CASE 
   WHEN DATEDIFF(dd, GETDATE(), CAST('20121025' AS DATE)) >= 31 THEN 'Blocked' 
   ELSE 'Not' 
 END);

Updated SQL Fiddle Demo

答案 1 :(得分:1)

select CASE 
   WHEN DATEDIFF(dd,@duedate,getdate()) >= 31 then 'Blocked' else 'NO' end