簡體   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