troubleshooting Question

Temporary table vs using nested query

Avatar of vb7guy
vb7guyFlag for United States of America asked on
Microsoft SQL Server 2005Microsoft DevelopmentMicrosoft SQL Server 2008
7 Comments1 Solution296 ViewsLast Modified:
I have the following query that pulls records from two tables and returns the data.  I'm using #temp table to accomplish this.  I'm inserting records into temp table from one query and then inserting some more records into the same temp table using the second query.  I'm returning the count and the list of records.  Is there a better/faster to accomplish the same result without using temp tables? Examples would be nice.

SELECT CompanyId,EmployeeId INTO #EmployeeList  
      FROM dbo.Employees l
      WHERE l.CompanyId > 0 AND EXISTS  
            (SELECT * FROM dbo.Filings f WHERE (f.CompanyId = l.CompanyId AND f.EmployeeId   = l.EmployeeId ) AND f.EmployeeId IS NOT NULL
                  AND f.Clientid IS NULL AND f.AddDateTime >= '01/01/2012' ) ;  
INSERT INTO #EmployeeList  
      SELECT DISTINCT  f.CompanyId,lof.EmployeeId  FROM dbo.Filings f  
            INNER JOIN dbo.EmployeesOnFiling lof ON lof.FilingId = f.FilingId  WHERE f.CompanyId > 0 AND f.ClientId IS NOT NULL
            AND f.EmployeeId IS NULL AND f.AddDateTime >= '01/01/2012'  ;

SELECT COUNT(*) as thecount FROM (SELECT DISTINCT CompanyId, EmployeeId       FROM #EmployeeList) as Tbl  ;
SELECT DISTINCT CompanyId, EmployeeId FROM #EmployeeList
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 7 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros