简体   繁体   English

在SQL Server中将Where In子句与表值用户定义函数一起使用

[英]Use Where In clause with Table-Valued User-Defined Function in Sql Server

I have a Table-Valued User-Defined Functions named "GetRelatedUsersIds", which in turn return all sub users (including itself) for any particular user if any. 我有一个名为“ GetRelatedUsersIds”的表值用户定义函数,该函数反过来返回任何特定用户(如果有)的所有子用户(包括自身)。

And I have a scenario where I want this function to be used in where in clause as given below:- 我有一种情况,我希望在下面的where in子句中使用此函数:

Create procedure [ABC]
(
@AddedBy Int,
@LoggedUser int=0
)
as
SELECT * FROM MyTable 
where AddedBy in (case when @AddedBy =0 then (select UserId from dbo.GetRelatedUsersIds(@LoggedUser)) else @AddedBy end)

Here I looking for variable @AddedBy if its 0 then I will go for variable @LoggedUser. 在这里,我寻找变量@AddedBy如果它为0,那么我将寻找变量@LoggedUser。

CREATE function [dbo].[GetRelatedUsersIds]
(
@ccManagerId INT
) 
returns @tableUsersId table(UserId int)
AS
.... code

But as UDF returns a table so I am getting an error of "Subquery returned more than 1 value". 但是,由于UDF返回了一个表,因此出现了“子查询返回的值大于1”的错误。

How to solve this issue, TIA. TIA如何解决此问题。

Pretty sure you need something like this. 很确定您需要这样的东西。 But don't use select *. 但是不要使用select *。 Instead you need to be explicit and use the column names you want. 相反,您需要明确并使用所需的列名。

SELECT * 
FROM MyTable 
where AddedBy in 
(
    select UserId 
    from dbo.GetRelatedUsersIds(@LoggedUser) 
    where @AddedBy = 0
)
OR 
(
    @AddedBy <> 0
    AND
    AddedBy = @AddedBy
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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