Sql server 选择与列相关的所有行

Sql server 选择与列相关的所有行,sql-server,Sql Server,我有一个Url表 UrlId Followedby 1 NULL 2 1 3 2 我想写一个以urlid为参数并返回所有行的sp。 GetAllurs 3 它将返回到行的上方 如果没有光标,上面的操作是否可行?看一看。看一看。使用递归函数,看起来是这样的 declare @UrlId int = 3 ;with C as ( select U.UrlId, U.Followedby from U

我有一个Url表

UrlId   Followedby
1            NULL
2            1
3            2
我想写一个以urlid为参数并返回所有行的sp。 GetAllurs 3 它将返回到行的上方

如果没有光标,上面的操作是否可行?

看一看。

看一看。

使用递归函数,看起来是这样的

declare @UrlId int = 3

;with C as 
(
  select U.UrlId,
         U.Followedby
  from Url as U
  where U.UrlId = @UrlId
  union all
  select U.UrlId,
         U.Followedby
  from Url as U
    inner join C
      on U.UrlId = C.Followedby
)
select UrlId,
       Followedby 
from C

使用递归

declare @UrlId int = 3

;with C as 
(
  select U.UrlId,
         U.Followedby
  from Url as U
  where U.UrlId = @UrlId
  union all
  select U.UrlId,
         U.Followedby
  from Url as U
    inner join C
      on U.UrlId = C.Followedby
)
select UrlId,
       Followedby 
from C

现在,我的DbAccess层中有一个对象,它是一个链表,加载所有链接,然后逐个加载url。我想保留链表,但喜欢在单个DB hit中加载所有url。现在,我的DbAccess层中有一个对象,它是一个链表,加载所有链接,然后逐个加载url。我想保留链表,但喜欢在单个DB hit中加载所有URL。我如何在我的案例中使用CTE。我的SP用于urlid。我如何在我的案例中使用CTE。我的SP用于urlid。