使用相同的选择多次与创建临时表

时间:2014-03-30 04:17:18

标签: sql sql-server

我有像

这样的代码
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

我正在选择并连接两个相同列的相同表格。如果我这样做:

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

哪一个会有更好的表现?创建临时表并重复使用多次或只选择多次?

1 个答案:

答案 0 :(得分:4)

如果数据在运行时没有在表上发生变化,并且所选择的行数低于10000-15000(取决于资源),我建议不要建议选择多个时间相同的查询。更好的是,如果我们可以在缓存中保留一次选定的数据并进行所需的操作。在这种情况下,变量表比临时表有好处,因为当查询范围结束时,变量表使用的资源也会被释放。