2

我正在系统之间进行数据转换,并准备了一个 select 语句,该语句标识了要从中提取table1和连接的必要行table2以显示一对支持列。此 select 语句还将空白列放入结果中,以便格式化结果以上传到目标系统。

除了这个查询之外,我还需要更新一些我想在新表中的单独语句操作中执行的列值。因此,我有兴趣将上述 select 语句作为 a 中的子查询运行,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;

我想执行上面的语句,以便将结果转储到一个新表中。任何人都可以请建议如何将语句嵌入到一个可以很好地与 a 配合使用的子查询中SELECT INTO

4

3 回答 3

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 ...

此外,您可能还想为您的表格使用别名,以使代码更具可读性;

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 子句之前已经有一个完全工作的选择查询。有些人还考虑在您的数据库 (tblName) 中使用匈牙利符号作为一种要避免的反模式。

于 2013-04-10T14:56:47.730 回答
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;
于 2013-04-10T14:47:41.907 回答
0

尝试

INSERT INTO stagingtable (AppId, ...)
SELECT ... --your select goes here
于 2013-04-10T14:39:05.497 回答