如何迭代CTE结果

时间:2017-02-03 09:16:08

标签: sql-server sql-server-2014

WITH cte AS
(
    SELECT MemberGroupID 
    FROM [dbo].[RoleMembers] WITH(NOLOCK) 
    WHERE RoleDefID = 1
)
SELECT * FROM cte

以上查询在我的存储过程中正常工作。但它会返回很多行,所以我想迭代所有行并使用MemberGroupID来调用另一个存储过程。

我该怎么做?

2 个答案:

答案 0 :(得分:3)

根据要求,不知道你的SP做什么/返回:

将CROSS APPLY视为子例程

示例1:

=INDEX(IF(Data!K:K<=10,"Indefinitely ",Data!K:K),MATCH('Missed On Sale'!D14&LEFT('Missed On Sale'!G14,(FIND(" -",'Missed On Sale'!G14,1)-1)),Data!F:F&Data!D:D,0))

示例2:

以下内容将按ID

拆分和取消分隔分隔的字符串
Select A.MemberGroupID 
      ,B.*
 From  [dbo].[RoleMembers] A
 Cross Apply [dbo].[fn_GroupMembers_HasMembershipe](1, A.MemberGroupID )  B
 WHERE RoleDefID = 1

返回

Declare @YourTable table (ID int, Value varchar(max))
Insert Into @YourTable values
(1,'New York;Albany;Providence'),
(2,'Atlanta;Kinderhook')

Select A.ID
      ,B.*
 From @YourTable A
 Cross Apply (
                Select RetSeq = Row_Number() over (Order By (Select null))
                      ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
                From  (Select x = Cast('<x>' + replace((Select replace(A.Value,';','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A 
                Cross Apply x.nodes('x') AS B(i)
              ) B

答案 1 :(得分:0)

Select B.*, A.MemberGroupID
From  [dbo].[RoleMembers] A
CROSS APPLY (Select db =  dbo.fn_GroupMembers_HasMembershipe(A.MemberGroupID,6))  B
WHERE RoleDefID = 1

这是在sqlserver 2014中使用Cross Apply的方式