我正在进行动态查询,我有点不确定如何完成此任务。这似乎是一种常见的东西,因此我会将其用作学习经验。
我的结构有几个表。我已经为这个例子中包含了一些,因为一旦我可以获得基本查询,我可以添加它。
在我的最终查询中,WHERE
子句将动态生成。
这是我的结构的一个小提琴:http://sqlfiddle.com/#!6/2b104
在内部选择c.
中,您会注意到我有一个名为localeID
的列。我需要能够在我的外WHERE
子句中查询它。
例如,localeID将链接到localeCodes
表,从那里,我有另一个名为locations
的表。最终结果将是"向我展示北美的一切"。好吧,我们知道localeID
8 =犹他州和犹他州在北美(当加入地点表时)。
以下是与OP保持一致的查询:
SELECT a.[trainingEventID],
a.[teTitle],
a.[teSource],
a.[teType],
a.[teMedium],
a.[teFlag],
a.[teCreator],
a.[teCreated],
a.[tePOC],
a.[teDirector],
a.[teTeammateImpact],
a.[teCustomerImpact],
a.[teComplexity],
a.[intID],
a.[teNeededBy],
a.[approver],
a.[approvalDate],
(SELECT b.[trainingEventID],
b.[segmentDate],
b.[nonProdHrs],
(SELECT c.[segmentID],
c.[localeID],
c.[teammateCount],
c.[leaderCount]
FROM BS_TrainingEvent_SegmentDetails AS c
WHERE c.[segmentID] = b.teSegmentID
FOR XML PATH ('detail'), TYPE, ELEMENTS, ROOT ('details'))
FROM BS_TrainingEvent_Segments AS b
WHERE b.trainingEventID = a.[trainingEventID]
FOR XML PATH ('segment'), TYPE, ELEMENTS, ROOT ('segments'))
FROM BS_TrainingEvents AS a
--WHERE c.[localeID] = '8'
FOR XML PATH ('event'), TYPE, ELEMENTS, ROOT ('events');
答案 0 :(得分:1)
我们如何加入这两个从属表格,以便根据您的c.localeID
缩小结果集:
SELECT a.[trainingEventID],
a.[teTitle] ,
a.[teSource] ,
a.[teType] ,
a.[teMedium] ,
a.[teFlag] ,
a.[teCreator] ,
a.[teCreated] ,
a.[tePOC] ,
a.[teDirector] ,
a.[teTeammateImpact] ,
a.[teCustomerImpact] ,
a.[teComplexity] ,
a.[intID] ,
a.[teNeededBy] ,
a.[approver] ,
a.[approvalDate] ,
( SELECT b.[teSegmentID],
b.[trainingEventID] ,
b.[segmentDate] ,
b.[nonProdHrs] ,
( SELECT c.[segmentID] ,
c.[localeID] ,
c.[teammateCount] ,
c.[leaderCount]
FROM BS_TrainingEvent_SegmentDetails AS c
WHERE c.[segmentID] = b.teSegmentID
AND c.segmentID = tesd.SegmentID
FOR
XML PATH('detail') ,
TYPE ,
ELEMENTS ,
ROOT('details')
)
FROM BS_TrainingEvent_Segments AS b
WHERE b.trainingEventID = a.[trainingEventID]
AND b.trainingEventID = tes.trainingEventID
FOR
XML PATH('segment') ,
TYPE ,
ELEMENTS ,
ROOT('segments')
)
FROM BS_TrainingEvents a
INNER JOIN BS_TrainingEvent_Segments tes ON a.trainingEventID = tes.trainingeventID
INNER JOIN BS_TrainingEvent_SegmentDetails tesd ON tes.teSegmentID = tesd.SegmentID
INNER JOIN BS_LocaleCodes as locale ON tesd.localeID = locale.localeID
INNER JOIN BS_Locations as loc ON loc.location = locale.location
WHERE loc.[location] = 'Arizona'
FOR XML PATH('event') ,
TYPE ,
ELEMENTS ,
ROOT('events');