我有3个通过数据库查询使用的表。
总体表
| Invoice | Product | Total | Delivered | Not Delivered |
---------------------------------------------------------
| 00001 | AAAA | 4 | null | null |
| 00001 | BBBB | 2 | null | null |
| 00001 | CCCC | 2 | null | null |
| 00002 | AAAA | 3 | null | null |
* OverallTable处于初始状态
DeliveredTable
| Invoice | Product | Delivered |
---------------------------------
| 00001 | AAAA | 2 |
| 00001 | BBBB | 2 |
| 00001 | CCCC | 0 |
| 00002 | AAAA | 3 |
NotDeliveredTable
| Invoice | Product | Not Delivered |
---------------------------------
| 00001 | AAAA | 2 |
| 00001 | BBBB | 0 |
| 00001 | CCCC | 2 |
| 00002 | AAAA | 0 |
问题是如何将已传递和未传递的数据插入到TotalTable中?
我尝试使用以下查询进行更新,但出现错误
子查询返回了多个值
UPDATE @OverallTemp
SET delivered =
(SELECT ddt.fqty FROM @DeliveredTemp ddt where ddt.PRODUCT=
[@OverallTemp].product)
WHERE EXISTS
(SELECT ddt.invoice FROM @DeliveredTemp ddt where ddt.invoice=
[@OverallTemp].invoice);
UPDATE @OverallTemp
SET notdelivered =
(SELECT sdt.qty FROM @NotDeliveredTemp sdt where sdt.PRODUCT=
[@OverallTemp].product)
WHERE EXISTS
(SELECT sdt.invoice FROM @NotDeliveredTemp sdt where sdt.invoice=
[@OverallTemp].invoice);
答案 0 :(得分:3)
您不使用<OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" PartnerClaimType="email" />
,只需对EXISTS
语句使用JOIN
:
UPDATE
答案 1 :(得分:1)
错误在这里告诉您问题,您的子查询返回了1行以上。
如果要使用数据集将INSERT
数据放入表中,则需要将该数据视为数据集,而不是标量值:
例如,对于您的第一次尝试,正确的查询将是(请注意,此查询是未测试的):
UPDATE OT
SET delivered = ddt.fqty
FROM @OverallTemp OT
JOIN @DeliveredTemp ddt ON ddt.PRODUCT= OT.product;
在第二个查询中尝试一下,如果遇到问题,请发表评论。
答案 2 :(得分:0)
您可以尝试使用UPDATE ...From ... JOIN
代替更新子查询。
update t1
set Delivered = t2.Delivered
from OverallTable t1
join DeliveredTable t2 on t2.Invoice = t1.Invoice
and t2.Product = t1.Product
update t1
set [Not Delivered] = t2.[Not Delivered]
from NotDeliveredTable t1
join NotDeliveredTable t2 on t2.Invoice = t1.Invoice
and t2.Product = t1.Product