[英]How to update a table using a subquery that returns multiple rows in SQL Server?
I'm trying to update the Table LIQUIDITYACCOUNT
using the field QUANTITY
which belongs to the table STOCKACCOUNT
. 我试图更新表
LIQUIDITYACCOUNT
使用领域QUANTITY
属于表STOCKACCOUNT
。 Both tables have foreign key CLIENT_ID. 两个表都具有外键CLIENT_ID。
update
lq
set
lq.AMOUNT = lq.AMOUNT + ( st.QUANTITY % @num) * @rompu
from
LIQUIDITYACCOUNT lq
inner join STOCKACCOUNT st on
lq.CLIENT_ID = st.CLIENT_ID
and
st.TITRE_ID = @id_titre
and
st.QUANTITY > 0
The table STOCKACCOUNT
contains informations about STOCKS
hold by a customer while the table LIQUIDITYACCOUNT
contains information about cash money. 该表
STOCKACCOUNT
包含有关信息STOCKS
由客户持有,而表LIQUIDITYACCOUNT
包含现金货币的信息。 If the result of the subquery contains one row, it work. 如果子查询的结果包含一行,则它起作用。 But it doesn't for multiple rows.
但这并不适用于多行。 And in this generally the case in my project since any customer can hold many shares of different stocks.
在我的项目中通常都是这种情况,因为任何客户都可以持有许多不同股票的股票。
How can I make it work when the subquery returns multiple rows. 当子查询返回多行时,如何使其工作。
Purpose of the update seems odd but here it is 更新的目的似乎很奇怪,但是在这里
update lq
set lq.AMOUNT = lq.AMOUNT + stt.qty * @rompu
from LIQUIDITYACCOUNT lq
join ( select st.CLIENT_ID, sum(st.QUANTITY % @num) as qty
from STOCKACCOUNT st
where st.TITRE_ID = @id_titre
and st.QUANTITY > 0
group
by st.CLIENT_ID
) stt
on stt.CLIENT_ID = lq.CLIENT_ID
So the primary key on your lq table can be pk. 因此,您的lq表上的主键可以是pk。 Then the SQL for updating lq.AMOUNT with this logic is:
然后,使用此逻辑更新lq.AMOUNT的SQL是:
UPDATE
lq
SET
lq.AMOUNT = sq.newvalue
FROM
(
SELECT
lq.AMOUNT + ( st.QUANTITY % @num) * @rompu AS newvalue,
lq.pk
FROM
LIQUIDITYACCOUNT lq
INNER JOIN
STOCKACCOUNT st
ON
lq.CLIENT_ID = st.CLIENT_ID
AND
st.TITRE_ID = @id_titre
AND
st.QUANTITY > 0
) AS sq
WHERE
lq.pk = sq.pk
@tysonwright , @paparazzo and @Dai thank you so much indeed. @tysonwright , @ paparazzo和@Dai确实非常感谢您。 I have found a solution using
cursor
and while
loop. 我找到了一个使用
cursor
和while
循环的解决方案。 Below is the code. 下面是代码。
declare @id_client as varchar(50)
declare @amount as money
declare liq_cursor cursor for
SELECT
lq.AMOUNT + ( st.QUANTITY % @num) * @rompu AS newvalue,
lq.CLIENT_ID
FROM
LIQUIDITYACCOUNT lq
INNER JOIN
STOCKACCOUNT st
ON
lq.CLIENT_ID = st.CLIENT_ID
AND
st.TITRE_ID = @id_titre
AND
st.QUANTITY > 0
OPEN liq_cursor
FETCH NEXT FROM liq_cursor into @amount,@id_client
---
WHILE @@FETCH_STATUS=0
BEGIN
update LIQUIDITYACCOUNT set AMOUNT=@amount,
DATEMODIF=GETDATE()
where CLIENT_ID=@id_client
FETCH NEXT FROM liq_cursor into @amount,@id_client
END
close liq_cursor
deallocate liq_cursor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.