sql临时表使用方法
创建
select [字段1,字段2,...,] into #TempTableName from table (#表示局部,##标签全局)
删除
drop table #TempTableName
实例:
select table1.* from table1 as table1 WITH (NOLOCK)
left join table2 as table2 WITH (NOLOCK)
on table1.number = table2.number
where table1.number in (‘1‘,‘2‘,‘3‘,‘4‘,.......);
当table1与table2都为大表,数据在千万级,这样的查询效率会急剧下降。
其中一个优化方式,可以使用临时表
SELECT table1.number INTO #temp FROM table1 as table1 WHERE table1.number in (‘1‘,‘2‘,‘3‘,‘4‘,.......);
select table1.* from table1 as table1 WITH (NOLOCK)
left join table2 as table2 WITH (NOLOCK)
on table1.number = table2.number
inner join #temp as temptable
on temptable.number = table1.number;
或者
where table1.number in (select number from #temp);//用到table1的索引,如果table1比#temp数据大,效率高
或者
where exists(select number from #temp where number=table1.number)//用到#temp的索引,如果table1比#temp数据大,效率低
drop table #temp;
这样的修改把in方式变成临时标签join的方式,能提高查询效率。