无法从成功创建的#temp 表中进行选择
DECLARE @tmp_tab VARCHAR(20)
SELECT @TMP_TAB = '#TMP_TAB_BANK' + CAST(USER_ID(USER) AS NVARCHAR)
+ CAST(@@SPID AS NVARCHAR)
EXEC('CREATE TABLE ' + @TMP_TAB + (ID INT NULL, NAME VARCHAR NULL)')
//Break point
EXEC('select * from ' + @TMP_TAB)
我正在使用 SQL Server 2005。在上面的代码中,我决定如何命名我的临时表。然后我创建临时表。如果我只运行这些代码,我会收到命令成功完成
消息。
但是,如果我执行最后一行代码来检索数据(好吧,我知道它是空的)我得到
无效的对象名称“#TMP_TAB_BANK157”
为什么我无法从刚刚创建的表中获取记录?如果未创建临时表那么为什么我没有收到任何警告?
DECLARE @tmp_tab VARCHAR(20)
SELECT @TMP_TAB = '#TMP_TAB_BANK' + CAST(USER_ID(USER) AS NVARCHAR)
+ CAST(@@SPID AS NVARCHAR)
EXEC('CREATE TABLE ' + @TMP_TAB + (ID INT NULL, NAME VARCHAR NULL)')
//Break point
EXEC('select * from ' + @TMP_TAB)
I'm working in SQL Server 2005. In the code above I decide what to name my temp table. Then I create the temp table. If I run just these codes I receive Commands completed successfully
message.
However if I execute the last line of code to retrieve the data (well, I know it's empty) I get
invalid object name '#TMP_TAB_BANK157'
Why can't I fetch records from a just created table? If the temp table was not created then why don't I get any warning?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
#TEMP
表只能在创建它们的上下文中使用。如果您在一个 spid 或连接中创建#temp1
,则无法从任何其他范围访问它,子作用域除外。如果您在动态 SQL 中创建
#TEMP
表,则需要在同一范围内从中进行选择。替代方案是:
##GLOBAL
临时表,它们有其自身的风险。#TEMP
tables are only available from the context they are created in. If you create#temp1
in one spid or connection, you can't access it from any other scope, except for child scopes.If you create the
#TEMP
table in dynamic SQL, you need to select from it in the same scope.Alternatives are:
##GLOBAL
temp tables, which have their own risks.