1

I have code like

select count(*) from(
select t1.col1, t1.col2, t1,col3, t2.col2 from table1 t1
left join table2 t2 on t1.col1=t2.col1) x

select * from(
select t1.col1, t1.col2, t1,col3, t2.col2 from table1 t1
left join table2 t2 on t1.col1=t2.col1) x
where x.col1 > 10

I'm selecting and joining same tables with same columns twice. If i do it like:

declare @table table(col1 int,col2 int,col3 varchar,col4 int)
insert into @table(col1,col2,col3,col4) select * from (
select t1.col1, t1.col2, t1,col3, t2.col2 from table1 t1
left join table2 t2 on t1.col1=t2.col1
) x
select count(*) from @table
select * from @table where col1>10

which one would have better performance? creating temp table and reusing it multiple times or just selecting multiple times?

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171

1 Answers1

5

I will not suggest selecting multiple time same query, if data are not changing on the table at run time and also number of rows selected are under 10000-15000 (depending on resources). Better is if we can hold once selected data in cache and make what ever manipulation required. Variable table have benefit over temp table in such case because when scope of query is over, resources utilized by variable table are also released.

  • That in and of itself is not a good reason to choose table variables over temporary tables. [This answer](http://stackoverflow.com/questions/11857789/when-should-i-use-a-table-variable-vs-temporary-table-in-sql-server) explains very clearly how you should make that choice. – Steve Pettifer Apr 01 '14 at 08:09
  • Yes, that is right but Temp table behave as real table and is accessible out of the current scope, so when multiple user access same procedure then conflict may arise while inserting and deleting records. – Aasish Kr. Sharma Apr 01 '14 at 13:22
  • 1
    Only global temporary tables (prefixed ##). Local temporary tables (prefixed #) are not available outside your session, even from sessions on the same connection/with the same username. Local temp tables are dropped when your session ends. In addition, table variables cannot have indexes (other than primary keys and unique constraints). This generally makes table variables unsuited to large data sets. – Steve Pettifer Apr 01 '14 at 14:03