从临时表查看数据

时间:2018-09-10 12:44:58

标签: sql-server error-handling temp-tables

我有以下查询

select VendorNumber,stuff( (select distinct ','+dbo.vendordata.InvoiceStatus
                               from dbo.vendordata
                               where dbo.vendordata.VendorNumber = dbo.vendordata.VendorNumber 
                               for xml path('')
                              ), 1, 1, ''
                            ) as InvoiceStatus
    into #temp_table3
    from dbo.vendordata
    group by VendorNumber

我正在使用一个模板来存储发票状态和供应商编号的结果。

select VendorNumber,InvoiceStatus  from #temp_table3

它给我抛出错误

Msg 2714, Level 16, State 6, Line 1
There is already an object named '#temp_table3' in the database.

如何从临时表查看数据,可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

临时表和其他本地临时对象按会话分开。因此,如果您不终止会话(在SSMS中关闭查询窗口,断开连接,关闭会话等),则临时表将保留。如果您多次运行该脚本,那么您将需要检查该脚本是否已存在并将其删除(始终建议避免使用此类问题)。

-- do a check if temp table exists first then drop it before running

IF OBJECT_ID('tempdb..#temp_table3') IS NOT NULL
    DROP TABLE #temp_table3


select VendorNumber,stuff( (select distinct ','+dbo.vendordata.InvoiceStatus
                               from dbo.vendordata
                               where dbo.vendordata.VendorNumber = dbo.vendordata.VendorNumber 
                               for xml path('')
                              ), 1, 1, ''
                            ) as InvoiceStatus
into #temp_table3
from dbo.vendordata
group by VendorNumber

答案 1 :(得分:0)

您还可以通过以下查询来检查临时数据库中是否存在临时表

if exists (
select 1 from tempdb.dbo.sysobjects o
where o.xtype in ('U')  
and o.id = object_id(N'tempdb..#Tempdata')
)
DROP TABLE #Tempdata;