Click here to Skip to main content
15,895,537 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have a query which returns few records. The Query result has a column 'ACCTID'. Now for each record i need to take the ACCTID and fetch record from other table. I tried it to do in C# but using loop, but it is taking lot of time. Pls suggest me how to do the same in SQL server side.

Overview of query is like below:



Main query:

SQL
Select NAME, CANCEL_DATE..., ACCTID from Table1;



What i need to do for ACCTID now is fetch data from two other tables for ACCTID fetched from above main query

:

SQL
select * from table2 where ACCTID=@ACCTID 


select * from table3 where ACCTID=@ACCTID



In the end i need to return all the records fetched from above two queries.

What I have tried:

currently I am trying to use cursor to get it done
Posted
Updated 23-Dec-18 23:08pm
v2
Comments
Richard MacCutchan 24-Dec-18 4:56am    
Have you considered using a stored procedure?

1 solution

Use a JOIN:
SQL
SELECT a.Name, a.Cancel_Date, b.*, c.* FROM Table1 a
JOIN Table2 b ON a.ACCID = b.ACCID
JOIN Table3 c ON a.ACCID = c.ACCID
WHERE a.ACCID = @ACCID
 
Share this answer
 
Comments
W Balboos, GHB 24-Dec-18 6:56am    
In general, and slightly leaving the scope of the question, would a DISTINCT directive be a good idea to add to this? Not knowing what the data looks like, the potential for any number of duplicate records exists (particularly if there's no unique id'ish type field in table2 or table3)?

Of course, they may want the duplicates.
OriginalGriff 24-Dec-18 7:13am    
As you say, it depends on exactly what they are trying to do!

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