Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm a newbie to SQL Server. Please help me to write the following Logic in a query.
If getnow() > today 4 PM
SELECT *
FROM table
WHERE MailDate is Tomorrow
SELECT *
FROM table
WHERE MailDate is Today
from table
where DATEDIFF(day, GETDATE(), maildate) = case when
DATEPART(hour, GETDATE()) >= 16 then 1 else 0
–
–
–
–
–
–
The idea here is to use the implication rewrite rule:
IF ( x ) THEN ( y ) is equivalent to ( NOT ( x ) OR y )
In your case
IF ( DATEPART(HOUR, CURRENT_TIMESTAMP) >= 16 )
THEN ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 1 )
is equivalent to
( NOT ( DATEPART(HOUR, CURRENT_TIMESTAMP) >= 16 )
OR ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 1 ) )
and is itself equivalent to
( ( DATEPART(HOUR, CURRENT_TIMESTAMP) < 16 )
OR ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 1 ) )
Re-writing the original ELSE
clause as an IF..THEN
statement in its own right:
IF ( DATEPART(HOUR, CURRENT_TIMESTAMP) < 16 )
THEN ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 0 )
is equivalent to (this time omiting the intermediate step)
( ( DATEPART(HOUR, CURRENT_TIMESTAMP) >= 16 )
OR ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 0 ) )
The two expression can then be writting in conjunctive normal form ("a series of AND
s)
SELECT *
FROM the_table
WHERE ( ( DATEPART(HOUR, CURRENT_TIMESTAMP) < 16 )
OR ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 1 ) )
( ( (DATEPART(HOUR, CURRENT_TIMESTAMP) >= 16
OR ( DATEDIFF(DAY, CURRENT_TIMESTAMP, MailDate) = 0 ) ) ;
I don't know the exact MS-syntax-dialect, but I'll try to prove that you don't need an IF or a CASE construct. I took @mellamokb 's reply as an example.
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)
–
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.