我正在开发一个项目,我使用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#的新手,需要编写某种递归查询来遍历每个redirectedurl,如果它在requesturl中,那么找到关联的redirectedurl。某些网址可能包含多个重定向。
答案 0 :(得分:1)
由于您在SQL Server数据库中拥有此数据,因此一种可能的方法是带递归的CTE 。 This explanation一开始看起来有些混乱,但我想如果你向下滚动到示例,将会清楚如何做到这一点。
这里不重复整个解释,这是一个这样的查询的例子:
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
答案 1 :(得分:0)
您可以创建一个字典,其中RequestedUrl
为关键字,RedirectedUrl
为值。所以一旦你找到requestedUrl你就可以找到它的redirectedURL,如果redirectedURL有一个redirectedURL,你也可以找到它。
答案 2 :(得分:0)
如果我找对你,你想要一个整洁的小C#函数来找到最后一个重定向,对吧? 在这种情况下,应该这样做:
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;
}