0

我目前在存储过程中有以下 SQL 语句;

SELECT [Id],
    [Path],
    [Title],
    [Description]
FROM [Configuration].[Pages] p 
WHERE 
    ((p.Id = @Id) OR (@Id IS NULL)) AND
    ((p.Path = @Path) OR (@Path IS NULL))

这允许我传递页面的路径、页面的 id 或什么都不传递(返回全部)。

我希望对其进行重构以返回相关的子记录(1 到 M),而不是为返回的每条记录返回数据库。子记录的当前 SQL 如下;

SELECT     h.Id, h.Description, h.Title, h.[Content]
FROM            [Configuration].[HelpItems] h INNER JOIN
                         [Configuration].[PageHelpItems] ph ON h.Id = ph.HelpId
WHERE        (ph.PageId = @PageId)

目前,我正在遍历每个父记录并为每个记录调用此存储过程,我认为这效率低下,我希望使用 SP 使用一个或多个 SQL 语句来确保为所有父记录返回子记录。

4

2 回答 2

0

尝试使用以下查询:

SELECT     h.Id, h.Description, h.Title, h.[Content] 
FROM            [Configuration].[HelpItems] h INNER JOIN 
                     [Configuration].[PageHelpItems] ph ON h.Id = ph.HelpId 
                INNER JOIN [Configuration].[Pages] p ON ph.PageId = p.Id
WHERE     
    ((p.Id = @Id) OR (@Id IS NULL)) AND    
    ((p.Path = @Path) OR (@Path IS NULL))
于 2012-09-19T13:25:32.230 回答
0

所以你想要记录

;WITH Rec AS (
    SELECT [Id],
        [Path],
        [Title],
        [Description]
    FROM [Configuration].[Pages] p 
    WHERE 
        ((p.Id = @Id) OR (@Id IS NULL)) AND
        ((p.Path = @Path) OR (@Path IS NULL))
)
SELECT 'Main' Which, * FROM Rec
-- plus the children...
UNION ALL
SELECT 'Related', h.Id, h.Title, h.Description, h.[Content]
FROM   [Configuration].[HelpItems] h
INNER JOIN [Configuration].[PageHelpItems] ph ON h.Id = ph.HelpId
INNER JOIN Rec ON Rec.Id = ph.PageId
于 2012-09-19T13:45:27.713 回答