sql server使用另一个表中的数据更新表

时间:2013-01-31 07:03:55

标签: sql

我有两个表source_table和destination_table

源表见下文

orderid orderno invoiceno amount
 1         10       NULL    100
 2         NULL     11      200

我需要使用列

更新destination_table
orderid  orderno amount
  1         -      -
  2         -      -
  3         -      -

根据条件,源的orderid与目标orderid匹配

如果source orderno值不为null,那么该值应该在目标的orderno列中更新,否则source invoiceno应该在destination orderno列中更新

4 个答案:

答案 0 :(得分:1)

请尝试:

Update D
    SET orderno = (case when S.orderno is not null then orderno else s.invoiceno end)
FROM
    source_table S Join destination_table D
    ON S.orderid = D.orderid

答案 1 :(得分:1)

您有几种选择。一种选择是使用CASE

UPDATE d
SET d.OrderNo = 
   CASE 
     WHEN S.OrderNo IS NOT NULL THEN s.OrderNo END ELSE S.invoiceno END
FROM Source S 
    JOIN Destination D ON S.OrderId = D.OrderId

或者我个人更喜欢使用COALESCE

UPDATE d
SET d.OrderNo = COALESCE(S.OrderNo, S.InvoiceNo)
FROM Source S 
    JOIN Destination D ON S.OrderId = D.OrderId
祝你好运。

答案 2 :(得分:0)

Update D
SET orderno = S.orderno, amount = S.amount
FROM
source_table S Join destination_table D
ON S.orderid = D.orderid
WHERE S.orderno is not null

Update D
SET orderno = S.invoiceno, amount = S.amount
FROM
source_table S Join destination_table D
ON S.orderid = D.orderid
WHERE S.orderno is null

答案 3 :(得分:0)

如果您使用的是sqlserver,那么您也可以使用ISNULL函数。见下面的sql。

UPDATE D 
SET orderno = ISNULL(S.orderno, S.invoiceno), 
    amount =  S.amount 
FROM source_table S INNER JOIN destination_table D ON S.orderid = D.orderid 
WHERE S.orderno IS NOT NULL OR S.invoiceno IS NOT NULL