1、尽可能少用临时表
select * from
(select ROW_NUMBER()over(order by AreaName)as rowNum, AreaName,
AreaTotalPoints=(select SUM(Points) from #tempPoints where JurisdictionalUnitArea in(select AreaID from GetSubAreas(AreaID)))
from Areas where ParentAreaID=@AreaID)as t
where rowNum>(@pageindex-1)*@pagesize and rowNum<=@pageindex*@pagesize
我原来是这样写的:
select ROW_NUMBER()over(order by AreaName)as rowNum, AreaName,
AreaTotalPoints=(select SUM(Points) from #tempPoints where JurisdictionalUnitArea in(select AreaID from GetSubAreas(AreaID)))
into #temp from Areas where ParentAreaID=@AreaID
select * from #temp where rowNum>(@pageindex-1)*@pagesize and rowNum<=@pageindex*@pagesize
drop table #temp
测试后发现不用临时表查询时间大大减少了。
小结:有时我们为了语句的逻辑清晰而使用临时表存储数据,但这样会影响sql语句执行效率,特别在数据量大的时候,这种差异尤为明显。所以要权衡选择。一般在数据量小时,使用它影响不大。
2、尽可能少选取列
select tempUser.JurisdictionalUnitArea,SUM(pr.Points)as yearPoints into #tempUser2
from #tempUser tempUser inner join PointRecords pr on tempUser.UserID=pr.EffectUserID。。。
我原来是这样写的:
select tempUser.* ,SUM(pr.Points)as yearPoints into #tempUser2
from #tempUser tempUser inner join PointRecords pr on tempUser.UserID=pr.EffectUserID。。。
其实自己需要用到的只是其中一部分数据列,有时为了图方便,就用*代替了,这样也会影响效率。
3、SET NOCOUNT 不返回计数功能
使用语句:SET NOCOUNT ON, 默认情况下(即不写)SET NOCOUNT 为OFF
一般使用sql server管理工具新建存储过程会自动创建这条指令,在不需要数据库告诉你执行完sql语句影响了多少行时推荐SET NOCOUNT ON,可以提高性能。
4、有无必要使用distinct
SELECT distinct u.*,ue.JurisdictionalUnitArea
和
SELECT u.*,ue.JurisdictionalUnitArea
distinct是返回数据表中不重复的记录,像注册用户这种情况一般在注册时就会验证唯一性,所以表中不会出现重复记录(其它情况可具体分析),就可以不使用distinct。
distinct和not in ,union等一样会导致全表扫描,导致性能下降,在能不用的情况下尽量不用。
补充:一般使用rowNumber()函数代替not in
使用union all 代替union