存储过程优化执行计划?
如果存储过程中有多个 if 条件,我猜执行计划的优化程度会较低,那么下面的后者是否更好?
if not exists (select * from accounts)
begin
raiseerror('error', 16, 1);
end
begin try
select 1/0 from accounts
end try
begin catch
raiseerror('error', 16,1)
end catch
If you have multiple if conditions in a stored procedure, I'm guessing the execution plan is going to be less optimized so is the latter below better?
if not exists (select * from accounts)
begin
raiseerror('error', 16, 1);
end
begin try
select 1/0 from accounts
end try
begin catch
raiseerror('error', 16,1)
end catch
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SQL Server 会更好地优化 Not Exists,因为你告诉它你想要什么。它可以跳过整个“检索(很多)行”,并且如果存在任何行,则仅传回布尔值 true/false
SQL Server will optimize the Not Exists better because you're telling it what you want. It can skip the whole "retrieve a (lot of) rows" and just pass back a boolean true/false if any rows exist
优化最好在实时系统上确定(或在测试中尽可能接近),因为“您的里程可能会有所不同”。但是,如果您想查看帐户表中是否有任何记录,只需执行
SELECT COUNT(*) from accounts
即可。使用不存在通常不利于优化,因此这种情况更容易一些。
Optimization is best determined on the live system (or as close as you can get in test) since "your mileage may vary". However, if you are looking to see if there are any records in the accounts table, just do
SELECT COUNT(*) from accounts
.Using a not exists is usually bad for optimization, so this case is a bit easier.