Click here to Skip to main content
15,997,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to fetch data from a table (say AutoReturnPostingDetails) or from another table (say Paramconfig) based on status with in a main select query in sql.

My query is as below:
select  id,                           
CASE WHEN ITCFinal.AutoReturnStatus=7004          
      THEN (select DebitAccNo from AutoReturnPostingDetails AP         
      where AP.OutwardInstFinalId=ITCFinal.OutwardInstFinalId)        
      ELSE @DebitAccount END AS DebitAccount       
                                         
                                          
 FROM OUT_ITC_Final ITCFinal 


What I have tried:

Select  id,                           
CASE WHEN ITCFinal.AutoReturnStatus=7004          
      THEN (select DebitAccNo from AutoReturnPostingDetails AP         
      where AP.OutwardInstFinalId=ITCFinal.OutwardInstFinalId)        
      ELSE @DebitAccount END AS DebitAccount       
                                         
                                          
 FROM OUT_ITC_Final ITCFinal
Posted
Updated 7-Sep-17 9:53am

1 solution

You'll want to use a join instead. Essentially, if I understand your attempt at SQL correctly, you want to use the DebitAccNo from a matching record if it exists and if it does not you want to use the passed in parameter. Use LEFT JOIN for this.

SQL
SELECT id, COALESCE(t2.DebitAccNo, @DebitAccount) 
FROM OUT_ITC_Final t1 
LEFT JOIN AP.OutwardInstFinalID t2 ON t1.OutwardInstFinalID = t2.OutwardInstFinalID
WHERE t1.AutoReturnStatus = 7004


Something along these lines.
 
Share this answer
 
Comments
[no name] 8-Sep-17 4:48am    
This will not work. It takes the first value if there on joining. I used a scalar function and passed the parameter as required and returned Account no based on the condition.
ZurdoDev 8-Sep-17 7:33am    
I don't follow, but if you got it working, good for you. It still sounds like you are overcomplicating it.

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