sql select into子查询

时间:2013-04-10 14:36:19

标签: sql sql-server-2005

我正在系统之间进行数据转换,并准备了一个select语句,用于标识从table1拉出的必要行,并加入table2以显示一对支持列。此select语句还会在结果中放置空白列,以便格式化上载到目标系统的结果。

除了这个查询之外,我还需要更新一些列值,我想在新表中的单独语句操作中执行这些操作。因此,我有兴趣将上面的select语句作为SELECT INTO中的子查询运行,这将基本上将结果放入临时表中。

SELECT 
    dbo_tblPatCountryApplication.AppId, '', 
    dbo_tblPatCountryApplication.InvId,
    'Add', dbo_tblpatinvention.disclosurestatus, ...
FROM 
    dbo_tblPatInvention 
INNER JOIN 
    dbo_tblPatCountryApplication ON dbo_tblPatInvention.InvId = dbo_tblPatCountryApplication.InvId
ORDER BY 
    dbo_tblpatcountryapplication.invid;

我想执行上面的语句,以便将结果转储到新表中。任何人都可以建议如何将语句嵌入到与SELECT INTO完美匹配的子查询中?

3 个答案:

答案 0 :(得分:1)

您只需在现有查询中添加INTO子句即可创建一个填充查询结果的新表:

SELECT ...
INTO MyNewStagingTable -- Creates a new table with the results of this query
FROM MyOtherTable
    JOIN ...

但是,您必须确保每列都有一个名称,如:

SELECT dbo_tblPatCountryApplication.AppId, -- Cool, already has a name
    '' AS Column2, -- Given a name to create that new table with select...into
    ...
INTO MyNewStagingTable
FROM dbo_tblPatInvention INNER JOIN ...

另外,您也可以使用aliases for your tables来使代码更具可读性;

SELECT a.AppId,
    '' AS Column2,
    ...
INTO MyNewStagingTable
FROM dbo_tblPatInvention AS i
    INNER JOIN dbo_tblPatCountryApplication AS a ON i.InvId = a.InvId
ORDER BY a.InvId

最后一个注意事项是,将表dbo_tblXXX命名为奇怪的,因为dbo通常是模式名称,并且使用点表示法与表名分隔,例如, dbo.tblXXX。我假设你在添加into子句之前已经有一个完全工作的select查询。有些人还考虑在数据库中使用匈牙利表示法(tblName)作为一种要避免的反模式。

答案 1 :(得分:0)

尝试

INSERT INTO stagingtable (AppId, ...)
SELECT ... --your select goes here

答案 2 :(得分:0)

如果登台表不存在而您想在插入时创建它,请尝试以下操作:

SELECT dbo_tblPatCountryApplication.AppId,'', dbo_tblPatCountryApplication.InvId,
       'Add', dbo_tblpatinvention.disclosurestatus .......
INTO StagingTable
FROM dbo_tblPatInvention 
INNER JOIN dbo_tblPatCountryApplication 
              ON dbo_tblPatInvention.InvId = dbo_tblPatCountryApplication.InvId;

如果要按特定顺序插入它们,请使用from子句中的子查询:

SELECT *
INTO StagingTable
FROM 
(
   SELECT dbo_tblPatCountryApplication.AppId, '', dbo_tblPatCountryApplication.InvId, 
          'Add', dbo_tblpatinvention.disclosurestatus .......
   FROM dbo_tblPatInvention 
   INNER JOIN dbo_tblPatCountryApplication ON 
              dbo_tblPatInvention.InvId = dbo_tblPatCountryApplication.InvId
    order by dbo_tblpatcountryapplication.invid
) a;