【问题标题】:Select * into #table from execute(@query)Select * into #table from execute(@query)
【发布时间】:2016-01-11 08:32:42
【问题描述】:

我创建了一个动态查询,它返回表中的列数:

set @query = 'select '+@cols+' from [Sample] '

现在我想通过执行这个查询来填充一个临时表,当我尝试这个时

select * into #table from execute(@query). 

我收到以下错误:

关键字“执行”附近的语法不正确

')' 附近的语法不正确

但是运行此命令会准确返回结果:execute(@query)

注意:我尝试过 sql-azure 不支持的 OPENROWSET。

如果还有其他解决方法,请提供帮助。

【问题讨论】:

  • 语法是insert #table execute(@query),但这需要#table已经存在,这意味着你必须知道正确的列定义才能创建它,这可能不是这种情况。跨度>

标签: database tsql azure-sql-database select-into


【解决方案1】:

尝试使用 FQ 表名而不是 #temptable:

 IF object_id('tempdb..temptable') IS NOT NULL DROP TABLE [tempdb].[dbo].[temptable] 
 DECLARE @query varchar(4000)
 SET @query = 'select '+ @cols +' into [tempdb].[dbo].[temptable] from [Sample]'

 EXECUTE (@query)

 SELECT * from [tempdb].[dbo].[temptable] 

请在SQLFiddle查看结果

【讨论】:

  • 列数将是动态的,因此我无法在插入之前创建表。
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-28
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多