Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Friends,
I have 2 table
1. Account<br />
2. Closed Account


I want list of account which is not closed.

I have tried following

SELECT distinct  vwA.AccountID,vwA.AccountName                         
  FROM vwAccounts  vwA       
  inner JOIN RMT_RiskAssessmentPlan AP ON AP.Accountcode = VWA.AccountID                        
  WHERE AP.[Year] = 2013 AND   
        VWA.AccountID NOT IN (SELECT AccountCode FROM RMT_ClosedAccount WHERE [YEAR] = 2013)            
  order by vwA.AccountName 


How can i replace the in clause with exists in following query?

I tired following
SELECT distinct  vwA.AccountID,vwA.AccountName
 FROM vwAccounts  vwA
 inner JOIN RMT_RiskAssessmentPlan AP ON AP.Accountcode = VWA.AccountID
 WHERE AP.[Year] = 2013 AND not exists(SELECT AccountCode FROM RMT_ClosedAccount WHERE [YEAR] = 2013)
 order by vwA.AccountName


But it returned me 0 result

Any idea how to use the exists clause?

Thanks in advance
Posted
Updated 26-Sep-13 23:30pm
v2

Based on the query you posted, the below query should give you the desired result-

SELECT distinct vwA.AccountID,vwA.AccountName
FROM vwAccounts vwA
inner JOIN RMT_RiskAssessmentPlan AP ON AP.Accountcode = VWA.AccountID
WHERE AP.[Year] = 2013 AND
NOT EXISTS(SELECT * FROM RMT_ClosedAccount WHERE [YEAR]=AP.[YEAR])
order by vwA.AccountName
 
Share this answer
 
Comments
dhage.prashant01 27-Sep-13 5:31am    
I have update my question.
Not exists gives me 0 record and if i use exists it gives me closed as well as open account
Sorry .... i missed one condition. Try the below query -

SELECT distinct vwA.AccountID,vwA.AccountName
FROM vwAccounts vwA
inner JOIN RMT_RiskAssessmentPlan AP ON AP.Accountcode = VWA.AccountID
WHERE AP.[Year] = 2013 AND
NOT EXISTS(SELECT * FROM RMT_ClosedAccount WHERE [YEAR]=AP.[YEAR] and ClosedAccount.AccountID=AP.AccountID)
order by vwA.AccountName
 
Share this answer
 
Comments
dhage.prashant01 27-Sep-13 5:46am    
How does it actually works??For every account in RMT_RiskAssessmentPlan it checks if ti closed or not.If it is not closed then that account is returned else it is skiped.Correct me if I'm wrong..
Madhu Nair 27-Sep-13 5:47am    
Is it working?
dhage.prashant01 27-Sep-13 5:50am    
Yes it working. Actually I was just checking to optimise the query. But both IN and EXISTS Query Cost is 100%
Madhu Nair 27-Sep-13 5:51am    
With me EXISTS always performed better than IN Queries. Please marked the question as answered which may help others 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