使用列中的现有值更新列中的null

时间:2018-09-04 19:20:11

标签: sql sql-server

通过下面的示例,我该如何使用已经存在的值(例如,用ORIGINAL_ORDER_NO更新9007853627空值,以及如何用等效的{{1} }?

我将传递original_order_line_no,脚本需要更新其余部分。

ORDER_LINE_NO

所需的输出:

ORDER_NO

2 个答案:

答案 0 :(得分:3)

ISNULL是一种方法,@ yourParam是您要传递的ORDER_NO

update yourTable
set   original_order_line_no   = isnull(original_order_line_no,ORDER_LINE_NO)
     ,ORIGINAL_ORDER_NO   = (select top 1 ORIGINAL_ORDER_NO from yourTable where ORDER_NO = @yourParam)  
where ORDER_NO = @yourParam and ORIGINAL_ORDER_NO is null

答案 1 :(得分:1)

您可以使用:

WITH cte AS (
  SELECT *, MIN(ORIGINAL_ORDER_NO) OVER(PARTITION BY ORDER_NO) as s
  FROM tab
  WHERE order_no = ?
)
UPDATE cte
SET ORIGINAL_ORDER_NO = s
   ,original_order_line_no = ORDER_LINE_NO  
WHERE ORIGINAL_ORDER_NO IS NULL;

DBFiddle Demo