子查询使用IN语句返回多个值

时间:2013-12-01 00:29:12

标签: sql-server-2005

这是我的疑问。

select *, ROW_NUMBER() OVER ( ORDER BY str_league_name ) AS RowNumber    
from vw_leagues 
where p_league_id in 
( 
select f_league_id from udf_get_trg_get_distinct_leagues_mem_in(5,'5,60327,532,4388,4424,4404,60131,66315,36704,38258,38409,38768,38907,39092,40566,42194,42512,42738,42773,43427,48418,58169')
) 

此查询

select f_league_id from udf_get_trg_get_distinct_leagues_mem_in(5,'5,60327,532,4388,4424,4404,60131,66315,36704,38258,38409,38768,38907,39092,40566,42194,42512,42738,42773,43427,48418,58169')

返回

的数据集

f_league_id 20 21 24 25 31

但是我收到了这个错误:

Msg 512,Level 16,State 1,Line 5 子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

我没有使用上述任何操作数。我正在使用IN声明。为什么我收到此错误?

这是udf:

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION udf_get_trg_get_distinct_leagues_mem_in (@myint int,@ids varchar(max))
RETURNS TABLE
AS
RETURN 
(
SELECT distinct a.p_league_id as f_league_id
from tb_leagues a
inner join tb_league_groups b on (a.p_league_id = b.f_league_id)
inner join tb_group_members c on (b.f_group_id = c.f_group_id)
where 
    (
    a.f_member_id_creator = @myint
    or a.f_member_id_officer1 = @myint
    or a.f_member_id_officer2 = @myint
    or a.f_member_id_officer3 = @myint
    or a.f_member_id_officer4 = @myint
    or a.f_member_id_officer5 = @myint
    )
or c.f_member_id in (select number from dbo.iter$simple_intlist_to_tbl(@ids))
)
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

这是函数中的函数

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION [dbo].[iter$simple_intlist_to_tbl] (@list nvarchar(MAX))
   RETURNS @tbl TABLE (number int NOT NULL) AS
BEGIN
   DECLARE @pos        int,
           @nextpos    int,
           @valuelen   int

   SELECT @pos = 0, @nextpos = 1

   WHILE @nextpos > 0
   BEGIN
      SELECT @nextpos = charindex(',', @list, @pos + 1)
      SELECT @valuelen = CASE WHEN @nextpos > 0
                              THEN @nextpos
                              ELSE len(@list) + 1
                         END - @pos - 1
      INSERT @tbl (number)
         VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
      SELECT @pos = @nextpos
   END
   RETURN
END
GO

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

2 个答案:

答案 0 :(得分:0)

问题可能在udf_get_trg_get_distinct_leagues_mem_in中,因为当使用IN运算符时,应该返回多个值。

您也应该测试重复值。

答案 1 :(得分:0)

没关系。问题出在vw_leagues,而不是函数。我在该查询中的子选择中的语句中没有前1名。