如何通过存储过程获取多个记录

时间:2013-12-26 09:14:30

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

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 

如果有单个记录,则轻易获取

在有多条记录的情况下,它会抛出子查询返回多个值的错误

请帮我检查多条记录

1 个答案:

答案 0 :(得分:0)

试试这个:

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