繁体   English   中英

C# 递归查询

[英]C# Recursive Query

我正在做一个项目,我使用 C# 填充来自多个来源的单个 MSSQL 表。

该表包含链接重定向信息(下面的示例结构)。

RequestedURL, RedirectedURL
www.123.com, www.123.com/123
www.123.com/123, www.123.com/1234/link.asp
www.123.com/1234/link.asp, www.123.com/12345/link.asp

我对 C# 非常陌生,需要通过每个重定向 URL 向 go 编写某种递归查询,如果它在请求的 URL 中,然后找到关联的重定向 URL。 某些 URL 可能有多个重定向。

由于您的 SQL 服务器数据库中有这些数据,因此一种可能的方法是CTE 与 recursion 这个解释一开始看起来有点混乱,但我认为如果你向下滚动到这个例子,就会很清楚如何做到这一点。

此处不重复整个解释,这是此类查询的示例:

USE AdventureWorks2008R2;
GO
WITH DirectReports (ManagerID, EmployeeID, Title, DeptID, Level)
AS
(
-- Anchor member definition
    SELECT e.ManagerID, e.EmployeeID, e.Title, edh.DepartmentID, 
        0 AS Level
    FROM dbo.MyEmployees AS e
    INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh
        ON e.EmployeeID = edh.BusinessEntityID AND edh.EndDate IS NULL
    WHERE ManagerID IS NULL
    UNION ALL
-- Recursive member definition
    SELECT e.ManagerID, e.EmployeeID, e.Title, edh.DepartmentID,
        Level + 1
    FROM dbo.MyEmployees AS e
    INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh
        ON e.EmployeeID = edh.BusinessEntityID AND edh.EndDate IS NULL
    INNER JOIN DirectReports AS d
        ON e.ManagerID = d.EmployeeID
)
-- Statement that executes the CTE
SELECT ManagerID, EmployeeID, Title, DeptID, Level
FROM DirectReports
INNER JOIN HumanResources.Department AS dp
    ON DirectReports.DeptID = dp.DepartmentID
WHERE dp.GroupName = N'Sales and Marketing' OR Level = 0;
GO

您可以创建一个字典,其中RequestedUrl作为键, RedirectedUrl作为值。 所以一旦你找到了requestedUrl,你就可以找到它的redirectedURL,如果redirectedURL 有redirectedURL,你也可以找到它。

如果我猜对了,你想要一个整洁的小 C# function 来找到最后一个重定向,对吧? 在这种情况下,应该这样做:

string GetRedirectionFromDatabase(string requestUrl)
{
  // Fetch redirect form DB, or if none exists return null
}

string GetFinalUrl(string requestUrl)
{
  var redirection = GetRedirectionFromDatabase(requestUrl);
  return redirection != null ? GetFinalUrl(redirection) : requestUrl;
}

暂无
暂无

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

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