使用连接从表值函数返回数据

时间:2015-04-28 12:29:40

标签: sql sql-server stored-procedures sql-server-2005

我有一个包含表值函数的查询。但是当执行此附加错误时。我该如何解决这个问题?

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)

Error

2 个答案:

答案 0 :(得分:3)

当您需要从函数返回多个值时,可以使用outer apply而不是subselect:

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)

答案 1 :(得分:1)

这是因为在将TVF用作子查询时需要返回单个列

在您的代码中,您从TVF返回Opening,Topup1,Topup2,Topup3,Returnsv,SaleQty,SaleVal

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

您还需要确保只从子查询中获得一行。您可以将TOP 1ORDER BY一起使用,只获得一行