IF Condition in an SQL query

前端 未结 8 1678
长发绾君心
长发绾君心 2021-01-04 20:23

I\'m a newbie to SQL Server. Please help me to write the following Logic in a query.

If getnow() > today 4 PM
Then
    SELECT *
    FROM table
    WHERE M         


        
8条回答
  •  失恋的感觉
    2021-01-04 20:40

    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 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 ) )  ;
    

提交回复
热议问题