数据库中已经有一个名为"#result"的对象

use*_*310 3 sql sql-server-2005

Alter Procedure sp_Member(
  @comcode int = 0,
  @SubComCode int = 0
)
as begin
  set nocount on
  If @comcode='0'
  begin
    select (
      select sum(amount)
        from tbcoudet
        where memcode=tbm.memcode and
              expyear=(select max(expyear) from tbexpyear)
              and exists (
                select itemcode
                from tbitem
                where comcode=@comcode and
                  SubComCode=@SubComCode and
                  itemcode=tbcoudet.itemcode
              )
        group by memcode,expyear
      )'TurnOver', *
    into #result from tbmember tbm where can_flag='N'
  end
  If @subcomcode='0'
  begin
    select (
      select sum(amount)
      from tbcoudet
      where memcode=tbm.memcode and expyear=(select max(expyear) from tbexpyear)
        and exists (
          select itemcode
          from tbitem
          where comcode=@comcode and
            itemcode=tbcoudet.itemcode
        )
      group by memcode,expyear
    )'TurnOver', *
    into #result from tbmember tbm where can_flag='N'
  end

  select top 10 * from #result where TurnOver is not null order by TurnOver desc
end
Run Code Online (Sandbox Code Playgroud)

那是我的sql代码,当我要执行存储过程时,我得到了错误

There is already an object named '#result' in the database.
Run Code Online (Sandbox Code Playgroud)

谁能告诉我这是什么问题?

mar*_*c_s 9

错误是:该名称已经有一个临时表 - 如果它已经存在,不要重新创建它....

问题在于你选择的方式 - 你有两个地方

select (columns)
into #result 
from tbmember tbm 
...
Run Code Online (Sandbox Code Playgroud)

第一次,这将创建临时表#result.第二次,你会得到错误 - 因为它无法创建一个已经存在的表.

所以你需要将代码更改为:

该代码将起作用,您将能够将两组数据插入临时表中.

  • 我想明确表达意图.当将proc的内容复制+粘贴到新的查询窗口进行测试等时也很方便.当然没有大问题;) (3认同)