Is it best practice and/or is there any performance benefits of creating temporary tables at the beginning of a SQL query versus as they're needed?
I checked an execution plan and the create table pieces of the query were not listed.
Here's an example of the 2 scenarios: (just an example of the layout, not real query)
-- Create temp tables as needed.
CREATE TABLE #TempA (test int, ...);
INSERT INTO #TempA (test, ...)
SELECT test, ...
FROM TableA;
CREATE TABLE #TempB (test int, ...);
INSERT INTO #TempB (test, ...)
SELECT test, ...
FROM TableB;
CREATE TABLE #TempC (test int, ...);
INSERT INTO #TempC (test, ...)
SELECT test, ...
FROM TableC;
DROP TABLE #TempA;
DROP TABLE #TempB;
DROP TABLE #TempC;
--Versus - Create temp at beginning of query
CREATE TABLE #TempA (test int, ...);
CREATE TABLE #TempB (test int, ...);
CREATE TABLE #TempC (test int, ...);
INSERT INTO #TempA (test, ...)
SELECT test, ...
FROM TableA;
INSERT INTO #TempB (test, ...)
SELECT test, ...
FROM TableB;
INSERT INTO #TempC (test, ...)
SELECT test, ...
FROM TableC;
DROP TABLE #TempA;
DROP TABLE #TempB;
DROP TABLE #TempC;