0

我有两个表 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 匹配

如果源 orderno 值不为空,则应在目标的 orderno 列中更新该值,否则应在目标 orderno 列中更新源 invoiceno

4

4 回答 4

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
于 2013-01-31T07:12:28.123 回答
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

祝你好运。

于 2013-01-31T07:12:32.537 回答
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
于 2013-01-31T07:26:06.013 回答
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
于 2013-01-31T07:06:57.370 回答