首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查询优化

查询优化
EN

Stack Overflow用户
提问于 2010-09-15 18:25:23
回答 3查看 162关注 0票数 0

我有一个这种格式的存储过程

代码语言:javascript
复制
if(condition 1)
begin
(
  -----
  -----
  select into #temp1
  ----
  drop #temp1
)
end
if(condition 2)
begin
(
  -----
  -----
  select into #temp1
  ----
  drop #temp1
)
end

现在,当执行上面的存储过程时,它向我显示了一个错误:

代码语言:javascript
复制
"There is already an object named '#temp1' in the database."

当我像这样修改存储过程时,

代码语言:javascript
复制
if(condition 1)
begin
(
  -----
  -----
  select into #temp1
  ----
  drop #temp1
)
end
if(condition 2)
begin
(
  -----
  -----
  select into #temp2
  ----
  drop #temp2
)
end

它的工作good.But我想优化这个,因为创建了太多的临时表。

有人能帮我解决这个问题吗?

EN

回答 3

Stack Overflow用户

发布于 2010-09-15 18:28:35

您可以在过程开始时删除该表。这有点棘手,但您可以检查是否存在临时表,如下所示:

代码语言:javascript
复制
if object_id('tempdb..#temp1') is not null
    drop table #temp1
票数 0
EN

Stack Overflow用户

发布于 2010-09-15 18:50:24

我会在条件语句之外创建/删除临时表,如下所示:

代码语言:javascript
复制
create table #temp ...

if(condition 1)
begin
(
  -----
  -----
  select into @temp
  ----
)
end
if(condition 2)
begin
(
  -----
  -----
  select into @temp2
  ----
)
end

drop table #temp

假设您的SQL Server版本支持它们,并且您知道日志记录和事务回滚方面的差异,则使用表变量可能更好。这样,您就不必担心它一旦超出范围就不会被丢弃。

票数 0
EN

Stack Overflow用户

发布于 2010-09-15 22:46:04

在第一个布局中,您可以尝试在if(condition 2)之前添加TRUNCATE TABLE #temp1,但是this question and accepted answer意味着表变量的性能会更好。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3716735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档