SQL Server 显示“无效的对象名称‘#temp’” 使用临时表时
我创建了一个过程
create procedure testProcedure_One
as
DECLARE @Query nvarchar(4000)
begin
SET @Query = 'SELECT * into #temptest FROM Table1'
Exec sp_Executesql @query
SELECT * FROM #temptest
drop table #temptest
end
当我运行过程 testProcedure_One
时,我收到错误消息:
无效的对象名称“#temp”
但如果我使用 ##temp 意味着
它正在工作:
create procedure testProcedure_two
as
DECLARE @Query nvarchar(4000)
begin
SET @Query = 'SELECT * into ##temptest FROM Table1'
Exec sp_Executesql @query
SELECT * FROM ##temptest
drop table ##temptest
end
testProcedure_two
工作正常
可能是什么问题? 我该如何解决它?
I have created a procedure
create procedure testProcedure_One
as
DECLARE @Query nvarchar(4000)
begin
SET @Query = 'SELECT * into #temptest FROM Table1'
Exec sp_Executesql @query
SELECT * FROM #temptest
drop table #temptest
end
When I run the procedure testProcedure_One
I am getting the error message:
Invalid object name '#temp'
But if I use ##temp means
it's working:
create procedure testProcedure_two
as
DECLARE @Query nvarchar(4000)
begin
SET @Query = 'SELECT * into ##temptest FROM Table1'
Exec sp_Executesql @query
SELECT * FROM ##temptest
drop table ##temptest
end
testProcedure_two
is working fine
What might be the issue? How can i solve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您有以下从 #temp 中进行选择的代码,给您带来错误?
这取决于范围。 ##temp 是全局临时表,在其他会话中可用。 #temp 是“本地”临时表,只能由当前执行范围访问。 sp_executesql 在不同的作用域下运行,因此它将把数据插入#temp,但如果您随后尝试在 sp_executesql 调用之外访问该表,它将找不到它。
例如
此错误是因为创建了 #Test 并且仅对 sp_executesql 上下文可见:
上面的内容适用于 ##Test,因为它创建了一个全局临时表。
这是有效的,因为 SELECT 是同一范围的一部分。
我的问题是:
Presumably you have following code that SELECTs from #temp, giving you the error?
It's down to scope. ##temp is a global temporary table, available in other sessions. #temp is "local" temporary table, only accessible by the current executing scope. sp_executesql runs under a different scope, and so it will insert the data into #temp, but if you then try to access that table outside of the sp_executesql call, it won't find it.
e.g.
This errors as #Test is created and only visible to, the sp_executesql context:
The above works with ##Test as it creates a global temporary table.
This works, as the SELECT is part of the same scope.
My questions would be:
使用CREATE TABLE 创建临时表,然后使用INSERT INTO 插入值而不是SELECT INTO。
这为我解决了这个问题。
Create the Temporary table by using CREATE TABLE and then use INSERT INTO to insert the values instead of SELECT INTO.
This rectified the problem for me.
为了让你执行,我认为应该首先使用 ddl 语句创建#tmp_table。
然后执行 exec,并且在 exec 中创建的存储过程应该具有相同的命名
临时表,即#tmp_table
。for you to execute i think that the #tmp_table should be created first using a ddl statement.
Then you execute your exec and the stored proc you have created in the exec should have the same named
temp table viz.#tmp_table
.