数据准备
代码如下 | 复制代码 |
create table tab1(name nvarchar(20),gold int) create table tab2(name nvarchar(20),gold int) --data insert into tab1 values('user1',10) insert into tab1 values('user2',10) insert into tab2 values('user1',20) |
2.update join更新记录
代码如下 | 复制代码 |
update tab1 set gold=t1.gold+t2.gold from tab1 t1 inner join tab2 t2 on t1.name=t2.name |
说明:两张表的数据一定要是一对一关系,否则更新结果可能不明确。
网上整理的两个句话
1.加回原消费金额
代码如下 | 复制代码 |
UPDATE e SET e.money = e.money + d.amount FROM employee e INNER JOIN (SELECT empid,amount=sum(amount) FROM deleted WHERE rechargeable=1 GROUP BY empid) d ON d.empid=e.id |
2.扣除新消费金额
代码如下 | 复制代码 |
UPDATE e SET e.money = e.money - i.amount FROM employee e INNER JOIN (SELECT empid,amount=sum(amount) FROM inserted WHERE rechargeable=1 GROUP BY empid) i ON i.empid=e.id |
时间: 2024-11-17 23:07:55