内部选择或连接的SQL查询数据

时间:2014-11-12 19:35:27

标签: sql sql-server tsql stored-procedures

我有一个基本格式的TSQL查询:

此查询的目标是查找L.localeID = x所有数据。正如您可以在查询中的第二个内部select语句中看到它。

我在内部选择中有这个,因为该表中的多个结果链接到父表。

如何以正确的格式获取此查询?我是否需要以特定方式加入表格或者子查询是否有效?

     SELECT A.[trainingEventID],
        A.[teTitle],
        A.[teDesc],
        A.[teSource],
        A.[teType],
        A.[teMedium],
        A.[teFlag],
        A.[teCreator],
        A.[teCreated],
        seg.[segmentDate],
        convert(decimal(10, 2), seg.[nonProdHrs]) as nonProdHrs,
        (
             SELECT emp.[FirstName] as trainerFirst,
                    emp.[LastName] as trainerLast
            FROM BS_Training_Trainers as trn
            LEFT OUTER JOIN employeeTable as emp
            ON trn.trainerEmpID = emp.EmpID
            WHERE trn.segmentID = seg.teSegmentID
            FOR    XML PATH ('trainer'), TYPE, ELEMENTS, ROOT ('trainers')
        ),
        (
         SELECT L.[recordID],
                L.[segmentID],
                L.[localeID],
                L.[teammateCount],
                L.[leaderCount]
            FROM dbo.BS_TrainingEvent_SegmentDetails AS L
            WHERE seg.teSegmentID = L.segmentID
            FOR    XML PATH ('detail'), TYPE, ELEMENTS, ROOT ('details')
        )
        FROM   [red].[dbo].[BS_TrainingEvents] AS A
        INNER JOIN dbo.BS_TrainingEvent_Segments AS seg
        ON A.[trainingEventID] = seg.[trainingEventID]

更新

这是一个SQL小提琴:http://sqlfiddle.com/#!6/fe3cf/11

1 个答案:

答案 0 :(得分:0)

您可以使用XQuery检查从dbo.BS_TrainingEvent_SegmentDetails生成的XML是否包含<localeID>200</localeID>。为此,您需要以可在WHERE中引用它的方式定义XML列。一种方法是使用CROSS APPLY:

CROSS APPLY
    (
     SELECT L.[recordID],
            L.[segmentID],
            L.[localeID],
            L.[teammateCount],
            L.[leaderCount]
        FROM dbo.BS_TrainingEvent_SegmentDetails AS L
        WHERE seg.teSegmentID = L.segmentID
        FOR    XML PATH ('detail'), TYPE, ELEMENTS, ROOT ('details')
    ) AS x (SegmentDetailsXML)

然后,您将主要选择中的值引用为x.SegmentDetailsXML,并且还可以在WHERE子句like this中使用它:

WHERE
    x.SegmentDetailsXML.exist('/details/detail/localeID[text() = "200"]') = 1

或者,如果200应该通过变量名传递,like this

WHERE
    x.SegmentDetailsXML.exist('/details/detail/localeID[text() = sql:variable("@localeID")]') = 1