sql server 存储过程的优化.(变量表,临时表的简单分析)
昨日一朋友发来一段sql的存储过程(如下),让我看看能不能优化一下。
insert @T1
select g_no,co_no,si_no,str_no,sum(ind_qty) as qty
from instock_detail where in_id = @id group by g_no,co_no,si_no,str_no
--?unitstock -->保存在变量表中
insert @T2
select a.*
from unitstock a,@T1 b
where a.g_no =b.g_no and a.co_no =b.co_no
and a.si_no =b.si_no and a.str_no=b.str_no
delete unitstock
from @T1 a
where unitstock.g_no=a.g_no and unitstock.co_no =a.co_no
and unitstock.si_no=a.si_no and unitstock.str_no=a.str_no
insert unitstock
select g_no,co_no,si_no,str_no,sum(qty) as qty from
( select * from @T1 union all select * from @T2
) AA
group by g_no,co_no,si_no,str_no
今日有空,作了一下变量表,临时表插入数据的性能分析。
1。变量表:
insert @T1
select g_no,co_no,si_no,str_no,sum(ind_qty) as qty
from instock_detail where in_id = @id group by g_no,co_no,si_no,str_no
--?unitstock -->保存在变量表中
insert @T2
select a.*
from unitstock a,@T1 b
where a.g_no =b.g_no and a.co_no =b.co_no
and a.si_no =b.si_no and a.str_no=b.str_no
delete unitstock
from @T1 a
where unitstock.g_no=a.g_no and unitstock.co_no =a.co_no
and unitstock.si_no=a.si_no and unitstock.str_no=a.str_no
insert unitstock
select g_no,co_no,si_no,str_no,sum(qty) as qty from
( select * from @T1 union all select * from @T2
) AA
group by g_no,co_no,si_no,str_no
今日有空,作了一下变量表,临时表插入数据的性能分析。
1。变量表:
declare @t table
(
id nvarchar(50),
supno nvarchar(50),
eta datetime
)
insert @t
select top 10000 id,supno,eta from 表
这一句执行sql需时间:16806ms
2。临时表:
create table #t
(
id nvarchar(50),
supno nvarchar(50),
eta datetime
)
insert #t
select top 10000 id,supno,eta
from 表
这一句执行sql需时间:76ms
3。不创建临时表,直接插入到临时表
select top 10000 id,supno,eta
into #t
from 表
这一句执行sql需时间:30ms
通过以上的分析,可以非常清晰的看出那个优,那个劣了。
以上只是简单的分析了一下。所以在存储过程中尽量合作临时表来存储临时数据,不要使用变量表。
分类:
数据库
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现