Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi All
I am facing a issue in applying a conditional 'if' in the where clause of the SQL query.
Here is the query. I have removed the unnecessary joins, columns names and multiple conditions in WHERE clause to make it readable.
SQL
SELECT TransactionId, TransactionDate , ProcessingDate FROM TransactionDetails
WHERE TransactionId in (2,3,9) AND ...AND ..

Now, I need to select the records from the TransactionDetails table with another transaction Ids 14 & 15 ONLY if the TransactionDate <> ProcessingDate for that particualr record.

What I tried:

Tried using IF ELSE - but it worked only with the variables. I want to apply the condition on the Dates columns from the table.

SQL
select  * from transactionDetails
WHERE OrderID in (400376, 400379)
AND
    IF TransactionDate <> ProcessingDate
        TransactionId in (2,3,9,14,15)
    ELSE
        TransactionId in (2,3,9)


I get two errors as -
Incorrect syntax near the keyword 'IF'.
Incorrect syntax near 'TransactionId'.

Please comment if you want me to improve my question
Posted
Updated 22-Mar-18 5:37am
v2
Comments
Member 10894637 1-Feb-18 5:13am    
And how to handle the condition where i only have "If" condition and not have any "else". i.e. I need to filter the records only when it is not null.

select * from transactionDetails
WHERE OrderID in (400376, 400379)
AND
IF TransactionDate IS NOT NULL
TransactionId in (2,3,9,14,15)

1 solution

Try:
SQL
select  * from transactionDetails
WHERE OrderID in (400376, 400379)
AND
    ((TransactionDate <> ProcessingDate AND TransactionId in (2,3,9,14,15)
    OR
     (TransactionDate = ProcessingDate AND TransactionId in (2,3,9)))
 
Share this answer
 
Comments
bbirajdar 5-Nov-12 6:17am    
It worked .. Thank you OG ..+5.. I wish I could have voted +50.. You saved me ..I have been scratching my head on this for a while...
OriginalGriff 5-Nov-12 6:59am    
Um...SA? :laugh:
bbirajdar 5-Nov-12 7:11am    
Sorry ..My mistake.. It was a typo.. Confused between the two great names on CP :)
Maciej Los 8-Nov-12 14:52pm    
+5!
Umesh AP 30-Mar-16 6:03am    
Thanks, Useful for me also.....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900