开发者

C# Recursive Query

I'm working on a project where i've used C# to populate a single MSSQL table of URLs from multiple sources.

The table contains link redirect info (example structure below).

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

I'm ver开发者_C百科y new to C# and need to write some sort of recursive Query to go through each redirectedurl, if it is in the requestedurl then to find the associate redirectedurl. Some URLs may have multiple redirects.


Since you have this data in your SQL Server database, one possible approach would be CTE's with recursion. This explanation looks a little confusing at first, but I think if you scroll down to the example it will be clear how to do this.

Without repeating the entire explanation here, this is an example of such a query:

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


You could create a dictionary with RequestedUrl as the key and RedirectedUrl as the value. So once you find the requestedUrl you could find its redirectedURL and if that redirectedURL has a redirectedURL, you could find that too.


If I get you right, you want a neat small C# function to find the last redirection, right? In that case this should do it:

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜