Sql server T-SQL更新联接1:N
我有两张桌子: 表1:Sql server T-SQL更新联接1:N,sql-server,Sql Server,我有两张桌子: 表1: id fee1 fee2 1 0.00 0.00 2 0.00 0.00 id fee_no fee 1 A 10.00 1 B 20.00 2 A 80.00 2 B 90.00 表2: id fee1 fee2 1 0.00 0.00 2 0.00 0.00 id fee_no fee 1 A 10.00 1 B
id fee1 fee2
1 0.00 0.00
2 0.00 0.00
id fee_no fee
1 A 10.00
1 B 20.00
2 A 80.00
2 B 90.00
表2:
id fee1 fee2
1 0.00 0.00
2 0.00 0.00
id fee_no fee
1 A 10.00
1 B 20.00
2 A 80.00
2 B 90.00
SQL:
执行此SQL后,只有table1
中的fee1
被更新,而fee2
没有更新。最后,我使用两条SQL语句分别更新fee1
和fee2
但是为什么这个SQL语句不起作用呢
下面是CREATETABLE语句:
create table table1(
id int null,
fee1 dec(30,2) null,
fee2 dec(30,2) null
)
insert into table1 (id,fee1,fee2)
select 1,0,0 union
select 2,0,0
create table table2(
id int null,
fee_no varchar(10) null,
fee dec(30,2) null
)
insert into table2 (id,fee_no,fee)
select 1,'A',10 union
select 1,'B',20 union
select 2,'A',80 union
select 2,'B',90
查询的问题是
table1
的每一行都会更新两次。但是,当第二次更新发生时,它将对表的原始数据进行操作。因此,fee2
被设置回0
要正确地更新
,您需要这样的查询:
update a
set a.fee1 = isnull(a.fee1, 0)
+ (case when b.fee_no ='A'
then cast(isnull(b.fee, 0) as decimal(30, 2))
else 0 end),
a.fee2 = isnull(a.fee2, 0)
+ (case when c.fee_no ='B'
then cast(isnull(c.fee, 0) as decimal(30,2))
else 0 end)
from table1 a
inner join table2 b on a.id = b.id and b.fee_no = 'A'
inner join table2 c on a.id = c.id and c.fee_no = 'B'
当c.fee\u no='B'时,您的更新显示为
大小写,但您的查询中没有分配表别名c
?抱歉,这是笔误。我已经修好了你能发布你的SQL吗?我打赌fee2
的第二次update
更新了不正确的值为什么在fee1
上没有发生同样的事情?在update
和select
query中feel
和fee2
之间有什么区别?