【问题标题】:Create Table using Schema of SQL Query使用 SQL 查询架构创建表
【发布时间】:2016-04-23 15:24:47
【问题描述】:

我需要从 sql 查询的返回模式创建表。在这里,sql 查询有多个连接。 示例 - 在以下场景中,为列“r”和“t”创建表架构。

select a.x as r b.y as t
from a
JOIN b
ON a.m = b.m

我不能使用“select into statement”,因为我得到一个输入 sql select 语句并且需要在运行时将该查询的输出复制到目标表。

【问题讨论】:

  • 看起来您正在寻找 insert into 子句。

标签: sql sql-server


【解决方案1】:

如果我正确阅读了您的问题,那么您是从外部源获取 SQL,并且您希望将其运行到表中(可能有数据,也可能没有数据)。应该这样做:

use tempdb;
declare @userSuppliedSQL nvarchar(max) = N'select top 10 * from Util.dbo.Numbers';

declare @sql nvarchar(max);

set @sql = concat('
with cte as (
', @userSuppliedSQL, '
)
select *
into dbo.temptable
from cte
where 9=0 --delete this line if you actually want data
;');
print @sql

exec sp_executesql @sql;
select * from dbo.temptable;

这假定提供的查询可以合法地用作公共表表达式的主体(例如,所有列都已命名且唯一)。请注意,您不能选择进入临时表(即#temp),因为临时表仅在sp_executesql 调用期间存在。

另外,出于对所有神圣事物的热爱,请理解,通过运行用户传入的任意 SQL,您正在向 SQL 注入敞开大门。

【讨论】:

  • 我了解 sql 注入的风险,并由其他接受用户请求的服务团队负责。
【解决方案2】:

我知道你说你不能选择进入,但是你能不能用 0=1 选择进入来创建一个空的表结构,然后再插入?

select a.x as r b.y as t
into TABLE
from a
JOIN b
ON a.m = b.m
where 0 = 1

【讨论】:

    【解决方案3】:

    在这里使用 into 子句。喜欢

    Select col1, col2, col3 
    into newtable 
    from old table;
    
    select a.x as r b.y as t 
    into c
    from a
    JOIN b ON a.m = b.m
    

    【讨论】:

    • 先创建结构然后使用总是更好的,所以你需要使用任何永远不会满足的条件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2012-03-10
    • 1970-01-01
    相关资源
    最近更新 更多