【问题标题】:Insert the data from Old table to new table, ID from new table and update for the corresponding row in old table. Most optimized way?将旧表中的数据插入新表,新表中的 ID 和旧表中相应行的更新。最优化的方式?
【发布时间】:2015-07-30 12:20:13
【问题描述】:

我有两张桌子。旧表和新表。 我需要将一些数据从旧表插入到新表,并从新表中获取 ID 并在旧表中更新相应行。 newtable ID 在 oldtable 中有单独的列,默认为 null。

一种方法是在将数据插入新表时从两个表中获取 ID,然后在旧表中查找数据并更新它。这是更简单的方法。

谁能提出一些优化的方法来做到这一点?

【问题讨论】:

  • 我没有看到任何“神奇”的更简单的方法;将数据插入newtable,记下现有和新创建的ID 值,更新oldtable .....
  • 是的,但是我需要跟踪来自 NEWTABLE 和 OLDTABLE 的 og ID,而且这两个表都很大,因此进行任何类型的额外操作都是昂贵的。所以我在想是否有任何方法可以在两个表中并行执行插入和更新。
  • 不,没有这种神奇的“同时更新两个表”的能力.....

标签: sql sql-server


【解决方案1】:

基本上,这里没有魔法 - 您需要将行插入 newtable 并跟踪 id 的 - 来自 oldtable 的“旧”行以及新表中的新行。

所以基本上,你需要这样的东西:

-- declare a helper table variable
DECLARE @TableOfID TABLE (OldID INT, NewID INT)  

-- insert rows into the "newtable" - OUTPUT the inserted ID (assuming it's INT IDENTITY)
-- and the "old ID" into the table variable
INSERT INTO dbo.newTable(OldID, Col1, Col2, ..., ColN)
OUTPUT Inserted.ID, Inserted.OldID INTO @TableOfID(NewID, OldID)
   SELECT 
       ID, Col1, Col2, .., ColN
   FROM 
       dbo.oldtable
   WHERE 
      ..... (some WHERE conditions here)

-- update the "oldtable"
UPDATE 
    dbo.oldtable
SET 
    NewID = t.NewID
FROM 
    @TableOfID t
WHERE
    dbo.oldtable.ID = t.OldID

【讨论】:

    【解决方案2】:
    -- declare a helper table variable
    DECLARE @TableOfID TABLE (OldID INT, NewID INT)
    
    MERGE newTable as target
    USING    (
        SELECT *
        FROM    oldtable
        ) AS source
    ON     (1=0) 
    WHEN NOT MATCHED BY TARGET THEN
    insert  ( OldID, Col1, Col2, ..., ColN)    
    VALUES (ID, Col1, Col2, .., ColN)
    OUTPUT Inserted.ID, Inserted.OldID INTO @TableOfID(NewID, OldID); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      • 2017-12-11
      • 2015-11-06
      • 1970-01-01
      相关资源
      最近更新 更多