Bau*_*aub 3 t-sql sql-server-2008
我有一个大的查询,首先选择#tmp1.在那个select语句之前我有以下内容:
USE Sandbox
--if the table exists, we want to delete it first
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = '#tmp1'))
BEGIN
drop table dbo.#tmp1
END
Run Code Online (Sandbox Code Playgroud)
问题是,当我运行整个查询时,我收到一个错误:
Msg 2714, Level 16, State 6, Line 51
There is already an object named '#tmp1' in the database.
Run Code Online (Sandbox Code Playgroud)
如果我突出显示上述语句并运行它,我得到:
Command(s) completed successfully.
但是如果我再次运行查询,我会得到上面的错误.
我也试过这两个(结果"成功完成",我在尝试运行查询时仍然遇到上述错误:
if exists (select * from sys.objects where name = '#tmp1' and type = 'u')
drop table dbo.#tmp1
IF OBJECT_ID('dbo.#tmp1', 'U') IS NOT NULL
DROP TABLE dbo.#tmp1
Run Code Online (Sandbox Code Playgroud)
任何人都可以看到我可能做错了什么?
我总共使用了4个临时表,我的大型SQL语句的结构如下:
USE Sandbox
If #tmp1 exists, drop it
If #tmp2 exists, drop it
If #tmp3 exists, drop it
If #tmp4 exists, drop it
Declare variables
select into #tmp1
select into #tmp2
select into #tmp3
select into #tmp4
select from #tmp1
select from #tmp2
select from #tmp3
select from #tmp4
Run Code Online (Sandbox Code Playgroud)
临时表存在tempdb...但您当前的代码正在检查Sandbox数据库中是否存在该对象.
更改代码以使用tempdb临时表所在的三部分名称(包括数据库):
IF OBJECT_ID('tempdb.dbo.#tmp1', 'U') IS NOT NULL
DROP TABLE dbo.#tmp1
Run Code Online (Sandbox Code Playgroud)