2013-04-10 78 views
2

我正在做一个系统之间的数据转换,并准备了一个select语句,标识从table1提取的必要行并将其加入table2以显示一对支持列。此选择语句还会将空白列放入结果中,以便将上载结果格式化为目标系统。sql select into subquery

除了这个查询之外,我还需要更新一些列值,我希望在新表中的单独语句操作中进行更新。因此,我有兴趣在SELECT INTO内将上述select语句作为子查询运行,这将基本上将结果放到暂存表中。

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匹配?

+2

你知道sql中的INSERT是干什么的吗? – marko 2013-04-10 14:38:39

回答

0

尝试

INSERT INTO stagingtable (AppId, ...) 
SELECT ... --your select goes here 
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; 
1

您可以简单地添加一个INTO cl澳洲英语到现有的查询来创建充满了查询结果的新表:

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)作为一种反模式来避免。