无法使用动态查询创建临时 table
Can't able to create temp table using Dynamic query
我正在尝试在 MS sql 服务器中创建临时 table。它显示 table 已创建并插入了值。使用 Select 查询时,会抛出错误。
我的示例代码是
EXEC (
'create table #temp2 (id int)
insert #temp2 values(1)'
)
SELECT *
FROM #temp2
输出为
(1 row affected)
Msg 208, Level 16, State 0, Line 8
Invalid object name '#temp2'.
在同一过程中创建临时 table,使其仍在范围内,然后使用动态 SQL 对其进行修改。
create table #temp2 (id int)
DECLARE @SQL NVARCHAR(1000) ='ALTER TABLE #temp2 ADD test1 int NOT NULL, test2 int NOT NULL'
EXEC sp_executesql @SQL
insert #temp2 values(1,2,3)
SELECT * FROM #temp2
DROP TABLE #temp2
我正在尝试在 MS sql 服务器中创建临时 table。它显示 table 已创建并插入了值。使用 Select 查询时,会抛出错误。
我的示例代码是
EXEC (
'create table #temp2 (id int)
insert #temp2 values(1)'
)
SELECT *
FROM #temp2
输出为
(1 row affected)
Msg 208, Level 16, State 0, Line 8
Invalid object name '#temp2'.
在同一过程中创建临时 table,使其仍在范围内,然后使用动态 SQL 对其进行修改。
create table #temp2 (id int)
DECLARE @SQL NVARCHAR(1000) ='ALTER TABLE #temp2 ADD test1 int NOT NULL, test2 int NOT NULL'
EXEC sp_executesql @SQL
insert #temp2 values(1,2,3)
SELECT * FROM #temp2
DROP TABLE #temp2