更新2个大表

时间:2015-09-09 09:55:34

标签: sql sql-server

我需要创建一个存储过程来更新到两个大表。

表1是项目表,表2是条形码表。

我有100000个项目需要连接到条形码。我希望在表1中插入条形码,并且当条形码在表1中时,我想填写“被采用”。

表1

 Id |Name   | Barcode
 1    item1    NULL
 2    Item2    Null

表2

Id |Barcode| isTaken | ItemId
14    123      0        NULL
321    321      0        NULL

使用免费条形码(istaken = 0)更新表1并使用带有条形码的项目更新表2中的itemId的最佳方法是什么?

我想要的结果示例:

表1

 Id |Name   | Barcode
 1    item1    123      
 2    Item2    321      

表2

Id |Barcode| isTaken | ItemId
14    123      1        Item1
321    321      1        Item2

请帮忙

3 个答案:

答案 0 :(得分:2)

您无法一次更新两个表格 你可以这样做(Cosidering ID是表1中的PK和表2中的FK):

BEGIN TRANSACTION;

    UPDATE A
    SET A.Barcode= B.Barcode
    FROM Table1 A
    INNER JOIN Table2 B
      ON A.Id=B.Id
    WHERE IsTaken=0

    UPDATE B
    SET B.ItemId= A.Name,
        B.IsTaken=1
    FROM Table1 A
    INNER JOIN Table2 B
      ON A.Id=B.Id
    WHERE IsTaken=0

COMMIT;

答案 1 :(得分:0)

由于无法加入id,您可以row_number加入:

begin transaction; set transaction isolation level serializable;

with tt1 as
( select row_number() OVER ( order by id ) as n1, 
         Name, id as id1, Barcode as Barcode1
  from t1
),
tt2 as 
( select row_number()  OVER ( order by id ) as n2, 
         Barcode as Barcode2, id as id2, ItemId
  from t2
  where isTaken = 0
),
j as 
( select id1, id2, Name, Barcode2, ItemId, Barcode1
  from tt1 inner join tt2 on tt1.n1 = tt2.n2 )
update j
  set j.ItemId = j.name;

with tt1 as
( select row_number() OVER ( order by id ) as n1, 
         Name, id as id1, Barcode as Barcode1
  from t1
),
tt2 as 
( select row_number()  OVER ( order by id ) as n2, 
         Barcode as Barcode2, id as id2, ItemId
  from t2
  where isTaken = 0
),
j as 
( select id1, id2, Name, Barcode2, ItemId, Barcode1
  from tt1 inner join tt2 on tt1.n1 = tt2.n2 )
update j
  set j.Barcode1 = j.Barcode2;

commit;

免责声明:未经测试。

答案 2 :(得分:-1)

查询可能是这样的......

更新table1 set Barcode =(从Table2中选择前1个条形码,其中isTaken为NULL) 其中Id =(从表1中选择前1个Id,条形码为NULL)

现在不要和我一起使用sql来检查语法。这需要在游标或while循环中进行更新到整个表。