資料更新 sql

2022-09-07 05:57:12 字數 1289 閱讀 8111

假設現在需要根據以下條件對該錶的資料進行更新。

對當前工資為 30 萬日元以上的員工,降薪 10%。

對當前工資為 25 萬日元以上且不滿 28 萬日元的員工,加薪 20%。

傳統方法

-- 條件一

update `user`

set salary = salary*0.9

where salary < 300000.00;

select * from `user`

-- 條件二

update `user`

set salary = salary*1.2

where salary > 250000.00 and salary < 280000.00;

select * from `user`

上邊這種方法是不正確的

原因:例如這裡有乙個員工,當前工資是 30 萬元,

按「條件 1」執行 update 操作後,工資會被更新為 27 萬元,

但繼續按「條件 2」執行 update 操作後,工資又會被更新為 32.4 萬元。

這樣,本來應該被降薪的員工卻被加薪了 2.4 萬元

即使將兩條 sql 語句的執行順序顛倒一下,當前工資為 27 萬日元 的員工,其工資的更新結果也會出現問題。

為了避免這些問題,可以像下面這樣用 case 表示式來寫 sql

case 表示式
-- 用 case 表示式寫正確的更新操作

update `user`

set salary = case

when salary >= 300000

then salary*0.9

when salary >=250000 and salary <280000

then salary*1.2

-- else salary非常重要,必須 寫上

else salary end;

select * from `user`;

注意

sql 語句最後一行的 else salary非常重要,必須 寫上。

因為如果沒有它,條件 1 和條件 2 都不滿足的員工的工資就會被更 新成 null。

圖例

SQL 資料更新

一般格式 insert into 表名 列名1 列明2 指出在表中新插入的值的列,values 常量1 常量2 指出在表中插入新值的列的具體值栗子1 將乙個新圖書元組插入到圖書表中。insert into 圖書 values a019 資料庫 王珊 高等教育出版社 33.8 本例中省略了 into ...

用SQL更新資料

更新資料使用的是 update 命令。4.8.1 直接賦值更新 1.語法 update 資料表 set 欄位名1 新的賦值,欄位名2 新的賦值,where 條件 2.例項 在 命令編輯區 執行以下語句。update scott.emp set empno 8888,ename tom hiredat...

SQL 資料更新 簡記

資料更新操作主要包括 所有需要操作的表都在這裡建立 insert into 表 屬性列1 屬性列2 value 常量1 常量2 示例1 插入單行資料 insert into stock mat num,mat name,speci,warehouse,unit,amount value m020 架...