TSQL临时过程:已经有一个名为的对象

时间:2017-08-11 10:54:41

标签: sql-server tsql stored-procedures temporary

已经回答了类似的问题,但仅限于临时表格。

我想按照

使用临时存储过程
-- test if folder exists, else create it
create procedure #mycheckcreatefolder
(
@rootfolder NVARCHAR(MAX),
@subfolder NVARCHAR (MAX)
)
as
BEGIN
      declare @full_path as NVARCHAR(MAX)
      declare @folder_exists as int
      declare @file_results table
      (file_exists int, file_is_a_directory int, parent_directory_exists int)
      select @full_path = @rootfolder + @subfolder

      insert into @file_results
      (file_exists, file_is_a_directory, parent_directory_exists)
      exec master.dbo.xp_fileexist @full_path

      select @folder_exists = file_is_a_directory
      from @file_results

      --script to create directory        
      if @folder_exists = 0
       begin
          print 'Directory does not exist, creating new one'
          EXECUTE master.dbo.xp_create_subdir @full_path
          print @full_path +  'created on' + @@servername
       end       
      else
        print 'Directory already exists'
END;
GO

-- use the stored procedure

但是当我反复执行查询时,我得到了

Msg 2714, Level 16, State 3, Procedure #mycheckcreatefolder, Line 30
There is already an object named '#mycheckcreatefolder' in the database.

第30行是"打印'目录已存在'"。

我删除了下面的所有代码,错误仍然会弹出。

同时添加

drop procedure #mycheckcreatefolder

最后没有帮助,开头的条件下降也是如此,从那时起我得到的错误是"创建程序"需要成为第一条指令。

有什么问题?

1 个答案:

答案 0 :(得分:2)

if object_id('tempdb..#sp_today') is not null drop proc #sp_today;
go

create proc #sp_today as
   select getdate() as dt;

您应该在tempdb中搜索它,而不是在当前数据库

中搜索它