简体   繁体   中英

Return Data from Table Valued Function with Joins

I have a query which contain table valued function. But when executing this attached error comming. How can I solve this?

SELECT bg.Description, im.ERPItemCode,
(select Opening,Topup1,Topup2,Topup3,
 Returnsv,SaleQty,SaleVal from dbo.GetOpeningByRepAcc(@Date,@RepAccId,@Cente![enter image description here][2]rId,im.Id)),
(select Name from dbo.DistributionCenter where Id = @CenterId) as center,
(select Name from dbo.SalesRepAcc where Id = @RepAccId)as repacc    
FROM BudgetGroup AS bg 
INNER JOIN  ItemMaster AS im ON bg.Id = im.BudgetGroupId
WHERE (bg.Active = 1)

错误

You can use outer apply instead of subselect when you need to return more than one value from function:

select
    bg.Description, 
    im.ERPItemCode,
    T1.Opening,
    T1.Topup1,
    T1.Topup2,
    T1.Topup3,
    T1.Returnsv,
    T1.SaleQty,
    T1.SaleVal,
    (select Name from dbo.DistributionCenter where Id = @CenterId) as center,
    (select Name from dbo.SalesRepAcc where Id = @RepAccId)as repacc    
from BudgetGroup AS bg 
    inner join  ItemMaster AS im ON bg.Id = im.BudgetGroupId
    outer apply dbo.GetOpeningByRepAcc(@Date,@RepAccId,@CenterId,im.Id) as T1
where (bg.Active = 1)

This is because you need to return a single column when using your TVF as a subquery

In your code you return Opening,Topup1,Topup2,Topup3,Returnsv,SaleQty,SaleVal from your TVF

((select Opening,Topup1,Topup2,Topup3,
 Returnsv,SaleQty,SaleVal from dbo.GetOpeningByRepAcc(@Date,@RepAccId,@CenterId,im.Id))

You also need to make sure you only get a single row from your sub-queries. you can use TOP 1 with ORDER BY to get only a single row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM