2011-06-01 100 views
0

我正在處理一個項目,我使用C#來填充來自多個源的URL的單個MSSQL表。C#遞歸查詢

該表包含鏈接重定向信息(下面的示例結構)。

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,如果是在requestedurl然後找到關聯redirectedurl。某些網址可能會有多個重定向。

+0

什麼碼你嘗試過這麼遠嗎? – 2011-06-01 10:51:36

+0

沒有一個MySQL查詢應該這樣做? – benwasd 2011-06-01 10:52:31

+0

@ben dotnet:DBMS是Microsoft SQL Server而不是MySQL。 – 2011-06-01 10:53:59

回答

0

您可以創建一個字典,其中RequestedUrl作爲鍵和RedirectedUrl作爲值。所以一旦你找到requestedUrl,你可以找到它的redirectedURL,如果這個redirectedURL有一個redirectedURL,你也可以找到它。

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