我想更新具有相同值的表中的多個列。例如,如果我們考慮這個表。
col1 col2
--------------
2 -99
-99 5
3 6
4 -99
我想將表中的 -99 值更新為 NULL,預期結果如下所示。
col1 col2
--------------
2 NULL
NULL 5
3 6
4 NULL
我正在使用這種方式。
update table_name set col1 = null where col1 = -99;
update table_name set col2 = null where col2 = -99;
或者,如果我想在唯一條件下更新列怎么辦。例如 -99 在 column1 中為 null,5 在 column2 中為 null。
有沒有辦法在單個陳述句中實作這一目標?提前致謝。
uj5u.com熱心網友回復:
您可以使用 case 運算式,但有什么好處?
update table_name set
col1 = case when col1 = -99 then null /* or any new value for col1 */ else col1 end
, col2 = case when col2 = -99 then null /* or any new value for col2 */ else col2 end
where col1 = -99 or col2 = -99;
請注意,正如 Larnu 所指出的,當您將列設定為 null 時,您可以將更新簡化為:
update table_name set
col1 = nullif(col1,-99)
, col2 = nullif(col2,-99)
where col1 = -99 or col2 = -99;
您可以將每列使用的值 (-99) 更改為您想要的任何值,例如 col2 = 5
update table_name set
col1 = nullif(col1,-99)
, col2 = nullif(col2,5)
where col1 = -99 or col2 = 5;
uj5u.com熱心網友回復:
您可以使用 NULLIF。
UPDATE null_table
SET co1 = NULLIF(col1,-99)
,col2 = NULLIF(col2,-99)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359841.html
上一篇:使用每個用戶的最后一個值填充表格
下一篇:如何使用查詢連接sql中的兩行
