我正在使用Microsoft SQL Server 2008 R2(RTM) - 10.50.1600.1(X64),我正在尝试将 SELECT 语句创建为一个像这样创建的表:< / p>
DECLARE @Sql AS VARCHAR(1500)
SET @Sql = 'SELECT 1 AS id, ''123'' AS value INTO #tmp_prueba'
EXECUTE ( @Sql )
SELECT * FROM #tmp_prueba
但我注意到该表不存在
如何从表格中获取数据?
答案 0 :(得分:4)
您在@sql中创建的临时表超出了外部查询的范围。
这是一种做你想做的事情的方法:
DECLARE @Sql AS VARCHAR(1500);
SET @Sql = 'SELECT 1 AS id, ''123'' AS value INTO #tmp_prueba;
select * from #tmp_prueba'
create table #tmp_prueba (id int, value varchar(255));
insert into #tmp_prueba
EXECUTE( @Sql );
SELECT * FROM #tmp_prueba
以下是更改。首先,我从@sql查询中的temproary表中选择所有内容。其次,我创建一个临时表(在这种情况下使用相同的名称)来保存结果。现在,我可以将执行结果插入表中。瞧!数据就在那里。
答案 1 :(得分:0)
临时表是在Tempdb上创建的,因此你也可以这样做:
SET @Sql = 'SELECT 1 AS id, ''123'' AS value INTO ##tmp_prueba'
EXECUTE ( @Sql )
Select * from tempdb..##tmp_prueba