Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server T-SQL更新联接1:N_Sql Server - Fatal编程技术网

Sql server T-SQL更新联接1:N

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

我有两张桌子:

表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       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
之间有什么区别?