【问题标题】:how to fetch multiple record by stored procedure如何通过存储过程获取多条记录
【发布时间】:2013-12-26 09:14:29
【问题描述】:
select 
   t.Sno, t.childid,
   (select customername as n from customerprofile c where c.cusid = t.childid) as name,t.earnedmoney as commission,
   (select p.bookingamt from propertyregistration p, customerprofile c where p.applicationno = c.applicationno and c.cusid = t.childid) as bookingamt,
   (select p.totalarea from propertyregistration p, customerprofile c where p.applicationno = c.applicationno and c.cusid = t.childid) as totalarea ,
   (select childid from tbl_level where parentid = t.childid) as child
from 
   tbl_level t 
where 
   parentid = @id 

这是过程

(select childid from tbl_level where parentid = t.childid) as child 

如果只有一条记录,它很容易获取

在多条记录中,子查询返回多个值会报错

请帮助我如何检索多条记录

【问题讨论】:

  • parentid 有 2 个或更多配置文件 (customerprofile) 或 propertyregistration 中有 2 个或更多行时,应该如何查询?
  • Bad habits to kick : using old-style JOINs - 旧式 逗号分隔的表格列表 样式已随 ANSI-92 SQL 标准(超过 20 年前)
  • 实际上我想显示特定记录的每个子项

标签: sql sql-server select left-join sql-server-group-concat


【解决方案1】:

试试这个:

SELECT t.Sno, t.childid, c.customername AS NAME, t.earnedmoney AS commission, 
       p.bookingamt AS bookingamt, p.totalarea AS totalarea, 
       MAX(STUFF(A.childid, 1, 1, '')) AS childs
FROM tbl_level t 
LEFT JOIN customerprofile c ON c.cusid = t.childid
LEFT JOIN propertyregistration p ON p.applicationno = c.applicationno 
CROSS APPLY(SELECT ' ' + t1.childid FROM tbl_level t1 WHERE t1.parentid = t.childid FOR XML PATH('')) AS A (childid)
WHERE parentid = @id 
GROUP BY t.Sno, t.childid, c.customername, t.earnedmoney, p.bookingamt, p.totalarea

从所有子 ID 中获取客户名称:

SELECT t.Sno, t.childid, c.customername AS NAME, t.earnedmoney AS commission, 
       p.bookingamt AS bookingamt, p.totalarea AS totalarea, 
       MAX(STUFF(A.customerNames, 1, 1, '')) AS childs
FROM tbl_level t 
LEFT JOIN customerprofile c ON c.cusid = t.childid
LEFT JOIN propertyregistration p ON p.applicationno = c.applicationno 
CROSS APPLY(SELECT ',' + c1.customername 
            FROM tbl_level t1 
            INNER JOIN customerprofile c1 ON c1.cusid = t1.childid
            WHERE t1.parentid = t.childid 
            FOR XML PATH('')
           ) AS A (customerNames)
WHERE parentid = @id 
GROUP BY t.Sno, t.childid, c.customername, t.earnedmoney, p.bookingamt, p.totalarea

【讨论】:

  • getting en error 列 'tbl_level.Sno' 在选择列表中无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。
  • 它的工作先生,您可以从每个正在提取的 childid 的 customerprofile 表中获取每个记录名称
  • @user2922694 您想要子 ID 还是只有客户名?
  • @user2922694 不客气。如果您发现任何问题和答案对您有帮助,您也可以通过点击右标记上方的向上箭头来投票
猜你喜欢
  • 2014-08-14
  • 2016-07-28
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多