子查询在 sqlc# 中返回超过 1 个值
Posted
技术标签:
【中文标题】子查询在 sqlc# 中返回超过 1 个值【英文标题】:Subquery returned more than 1 value in sqlc# 【发布时间】:2016-01-06 12:31:34 【问题描述】:在 ADO.Net 中运行的 SQL 命令字符串。问题它可能在子查询中返回超过 1 行。
string str = "
select
(select (quantity) from Orderinfo where iron=1 and rno=o.rno) as iron
,(select (quantity) from Orderinfo where wash=1 and rno=o.rno) as wash
,(select (quantity) from Orderinfo where dryclean=1 and rno=o.rno) as dryclean
,o.rno
,o.id
,o.name
,(select sum(convert(int,d.quantity)) from orderinfo as d where d.rno=o.rno) as quantity
,o.status
from orderinfo as o
where o.status='Order in Process'
group by o.rno,o.id ,o.status ,o.name";
【问题讨论】:
使用 select top 1....... 代替。 请谨慎对待您的 SQL 查询,它们应该与您的应用程序代码一样具有可读性、可维护性和清晰性。 【参考方案1】:如果我正确理解你想要的结果,你需要得到数量的总和:
string str = "
select
(select sum(quantity) from Orderinfo where iron=1 and rno=o.rno) as iron
,(select sum(quantity) from Orderinfo where wash=1 and rno=o.rno) as wash
,(select sum(quantity) from Orderinfo where dryclean=1 and rno=o.rno) as dryclean
,o.rno
,o.id
,o.name
,(select sum(convert(int,d.quantity)) from orderinfo as d where d.rno=o.rno) as quantity
,o.status
from orderinfo as o
where o.status='Order in Process'
group by o.rno,o.id ,o.status ,o.name";
顺便说一句,我假设您希望整个“o.rno”的数量独立于特定的“o.id”是正确的。否则不需要子查询。
【讨论】:
以上是关于子查询在 sqlc# 中返回超过 1 个值的主要内容,如果未能解决你的问题,请参考以下文章
SQL Server 子查询返回超过 1 个值。子查询遵循 =, !=, <, <= , >, >=
子查询返回超过 1 个值。当子查询跟随 = 或子查询用作表达式时,这是不允许的