我是SQL Server的新手。请帮我在查询中编写以下逻辑。
If getnow() > today 4 PM
Then
SELECT *
FROM table
WHERE MailDate is Tomorrow
Else
SELECT *
FROM table
WHERE MailDate is Today
答案 0 :(得分:8)
select *
from table
where DATEDIFF(day, GETDATE(), maildate) = case when
DATEPART(hour, GETDATE()) >= 16 then 1 else 0
end
答案 1 :(得分: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
答案 2 :(得分: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)
;
答案 3 :(得分: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 ) )
然后这两个表达式可以以联合正常形式(“一系列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 ) ) ;
答案 4 :(得分:1)
从mytable a中选择a.name,if(a.is_active ='t','Active','Inactive')
答案 5 :(得分:0)
您需要一个存储过程才能在SQL中执行此操作。请查看此处的文档http://msdn.microsoft.com/en-us/library/aa174792(v=sql.80).aspx
答案 6 :(得分: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。
答案 7 :(得分:0)
IF DATEPART(HOUR, GETDATE()) > 16
BEGIN
-- SELECT statement
END
ELSE
BEGIN
-- SELECT statement
END
它不必存储在存储过程中。