分配跟踪号并标记它

时间:2015-11-15 10:07:08

标签: sql-server

我有2张桌子

表1

Customer Name , Order id , Tracking Id 
sailesh , 23546 , NULL
nilesh , 26362 , NULL

表2

Tracking id , Used
RN167367 , No
RN47282 , NO

我希望在表1中为每个订单分配一个跟踪编号,然后将其标记为已使用。

提前致谢

1 个答案:

答案 0 :(得分:0)

首先分配跟踪号码,然后标记它们:

;with cte1 as(select *, row_number() over(order by orderid) rn
              from table1 where trackingid is null),
      cte2 as(select *, row_number() over(order by trackingid) rn 
              from table2 where Used = 'NO')
 update c1 set trackingid = c2.trackingid
 from cte1 c1
 join cte2 c2 on c1.rn = c2.rn


 update t2 set Used = 'YES'
 from table1 t1
 join table2 t2 on t1.trackingid = t2.trackingid