在 SQL 服务器中使用执行时不知道临时表

Don't know temp tables when use Execute in SQL Server

我有以下查询:

if OBJECT_ID('tempdb..#tmpTables') is not null 
    drop table #tmpTables
Execute('select TABLE_NAME into #tmpTables from '+@dbName+'.INFORMATION_SCHEMA.TABLES')

while (select COUNT(*) from #tmpTables)>0
begin
    //here is my statement
end

当我执行此查询时,出现此错误:

Invalid object name '#tmpTables'.

但是当查询变成这样时:

if OBJECT_ID('tempdb..#tmpTables') is not null 
    drop table #tmpTables
select TABLE_NAME into #tmpTables from INFORMATION_SCHEMA.TABLES
while (select COUNT(*) from #tmpTables)>0
begin
    //here is my code
end

有效。

我该怎么做?

Table 个以单个数字符号 (#) 为前缀的名称是 'Local temporary table' 个名称。

本地临时 table 在与 SQL 服务器实例的同一连接期间仅对其创建者可见,就像首次创建或引用 table 时一样。
用户与 SQL 服务器实例断开连接后,将删除本地临时 table。

并且当您通过 EXEC() 命令创建一个 Local Temporary Table 时,创建者将不是您,它会在完成该语句后断开连接,并且随着完成连接临时 table 断开。


您可以像这样使用 table 变量:

DECLARE @tmpTables TABLE(TABLE_NAME nvarchar(max))

insert into @tmpTables
(select TABLE_NAME from INFORMATION_SCHEMA.TABLES)