10

我是 SQL Server 的新手。请帮我在查询中编写以下逻辑。

If getnow() > today 4 PM
Then
    SELECT *
    FROM table
    WHERE MailDate is Tomorrow
Else
    SELECT *
    FROM table
    WHERE MailDate is Today
4

8 回答 8

8
select *
from table
where DATEDIFF(day, GETDATE(), maildate) = case when
    DATEPART(hour, GETDATE()) >= 16 then 1 else 0
end
于 2012-04-19T23:02:22.970 回答
3
IF datepart(hh, getdate()) >= 16
    BEGIN
        SELECT *
        FROM table
        WHERE DateDiff(day, getdate(), MailDate) = 1
    END
ELSE
    BEGIN
        SELECT *
        FROM table
        WHERE DateDiff(day, getdate(), MailDate) = 0
    END
于 2012-04-19T23:01:53.270 回答
1

这里的想法是使用隐含重写规则:

IF ( x ) THEN ( y )   is equivalent to  ( NOT ( x ) OR y )

在你的情况下

IF ( DATEPART(HOUR, CURRENT_TIMESTAMP) >= 16 ) 
   THEN ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 1 ) 

相当于

( NOT ( DATEPART(HOUR, CURRENT_TIMESTAMP) >= 16 ) 
   OR ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 1 ) ) 

并且本身等价于

( ( DATEPART(HOUR, CURRENT_TIMESTAMP) < 16 ) 
   OR ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 1 ) )

ELSE将原始条款重写为IF..THEN独立的语句:

IF ( DATEPART(HOUR, CURRENT_TIMESTAMP) < 16 ) 
   THEN ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 0 ) 

相当于(这次省略了中间步骤)

( ( DATEPART(HOUR, CURRENT_TIMESTAMP) >= 16 )
   OR ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 0 ) )

然后这两个表达式可以写成合取范式(“a series of ANDs) ”

SELECT *
  FROM the_table
 WHERE ( ( DATEPART(HOUR, CURRENT_TIMESTAMP) < 16 ) 
          OR ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 1 ) ) 
       AND 
       ( ( (DATEPART(HOUR, CURRENT_TIMESTAMP) >= 16
          OR ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 0 ) )  ;
于 2012-04-20T08:55:55.093 回答
1

select a.name, if(a.is_active='t','Active','Inactive') from mytable a

于 2013-10-22T06:06:23.900 回答
1

我不知道确切的 MS 语法方言,但我会尝试证明您不需要 IF 或 CASE 构造。我以@mellamokb 的回复为例。

SELECT *
  FROM the_table
 WHERE ( DATEPART(hour, GETDATE()) >= 16
           AND DATEDIFF(day, GETDATE(), MailDate) = 1)
    OR (DATEPART(hour, GETDATE()) < 16
           AND DATEDIFF(day, GETDATE(), MailDate) = 0)
     ;   
于 2012-04-19T23:49:42.887 回答
0
IF ( DATEDIFF(h, GETDATE(), DATEADD(h,4,GETDATE()))>0 )

SELECT *
FROM table
WHERE MailDate is Tomorrow

ELSE

SELECT *
FROM table
WHERE MailDate is Today

这是 MS SQL。如果您想做更多,那么如果您执行 BEGIN .... END,则只需在其中执行一个命令/选择。

于 2012-04-19T23:00:47.163 回答
0
IF DATEPART(HOUR, GETDATE()) > 16
BEGIN
    -- SELECT statement
END
ELSE 
BEGIN
    -- SELECT statement
END

它不必在存储过程中。

于 2012-04-19T23:05:16.137 回答
0

您需要一个存储过程在 SQL 中执行此操作。看看这里的文档http://msdn.microsoft.com/en-us/library/aa174792(v=sql.80).aspx

于 2012-04-19T22:58:44.050 回答