我是 SQL Server 的新手。请帮我在查询中编写以下逻辑。
If getnow() > today 4 PM
Then
SELECT *
FROM table
WHERE MailDate is Tomorrow
Else
SELECT *
FROM table
WHERE MailDate is Today
我是 SQL Server 的新手。请帮我在查询中编写以下逻辑。
If getnow() > today 4 PM
Then
SELECT *
FROM table
WHERE MailDate is Tomorrow
Else
SELECT *
FROM table
WHERE MailDate is Today
select *
from table
where DATEDIFF(day, GETDATE(), maildate) = case when
DATEPART(hour, GETDATE()) >= 16 then 1 else 0
end
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
这里的想法是使用隐含重写规则:
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 AND
s) ”
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 ) ) ;
select a.name, if(a.is_active='t','Active','Inactive') from mytable a
我不知道确切的 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)
;
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,则只需在其中执行一个命令/选择。
IF DATEPART(HOUR, GETDATE()) > 16
BEGIN
-- SELECT statement
END
ELSE
BEGIN
-- SELECT statement
END
它不必在存储过程中。
您需要一个存储过程在 SQL 中执行此操作。看看这里的文档http://msdn.microsoft.com/en-us/library/aa174792(v=sql.80).aspx