T-SQL : Sub Query to Join

Rahul Polaboina 181 Reputation points
2022-12-27T04:44:14.777+00:00

I have a select statement which has multiple selects inside a select and it is taking forever to execute because of the huge volume of the data , below is the query and the table structures, can I help modifying in to select with joins instead of sub query in the main select.

--Tables:  
   create table #dispense  
(  
  primarykeydispenseid int  
  ,ForeignKeyDispenseID int  
  ,ForeignKeyCodeListDistTypeID int  
)  
  
create table #Receive  
(  
  PrimaryKeyReceiveID int  
  ,ForgienKeyProtocolID int   
)  
create table #transfer  
(  
  PrimaryKeyTransferID int  
  ,ForeignKeyReceiveID int  
)  
create table #CodeList  
(  
  PrimaryKeyCodeListID int  
  ,CodeListParentCD varchar(20)  
  ,CodeListCD varchar(20)  
)  
--Query:  
  
select (  
SELECT ForgienKeyProtocolID  
FROM #Receive  
WHERE PrimaryKeyReceiveID = CASE disp.ForeignKeyCodeListDistTypeID  
WHEN (  
SELECT DISTINCT  PrimaryKeyCodeListID  
FROM #CodeList  
WHERE CodeListParentCD = 'transtype'  
AND CodeListCD = 'receive'  
)  
THEN DISP.ForeignKeyDispenseID  
ELSE (  
SELECT ForeignKeyReceiveID  
FROM #transfer  
WHERE PrimaryKeyTransferID = DISP.ForeignKeyDispenseID  
)  
END ) as acc  
from #dispense DISP  
Developer technologies Transact-SQL
{count} votes

1 answer

Sort by: Most helpful
  1. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2022-12-27T17:17:16.11+00:00

    You can rewrite your query with JOINs based on their relationship instead of this correlated query. You need to show your table relationship and better with some sample data and expected result.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.