SQL Server 用于 Xml 路径
我正在返回查询的 xml 结果。
给定两个表:
**Foo**
FooId int
FooName varchar(10)
**Bar**
BarId int
FooId int (FK)
BarName varchar(10)
我创建一个选择语句,如下所示:
SELECT
FooId,
FooName,
(
SELECT
BarId,
FooId,
BarName
FROM
Bar
WHERE
Bar.FooId = Foo.FooId
AND Bar.BarName = 'SomeBar'
FOR XML PATH('Bar'), TYPE
)
FROM
Foo
WHERE
Foo.FooName = 'SomeFoo'
AND Foo.FooId IN
(
SELECT
Bar.FooId
FROM
Bar
WHERE
Bar.BarName = 'SomeBar'
)
FOR XML PATH('Foo'), TYPE
这按我的预期工作并返回正确的结果。 我意识到在开发它时,我需要在子选择和 where 子句中的嵌套选择中复制过滤子句,以获得正确的结果。
我想确保没有更好的方法来做到这一点。 一位同事提到使用别名来删除重复的子句,但我不确定这将如何完成任何事情。
这个有必要吗,或者有更好的办法吗?
I am returning an xml result for a query.
Given two tables:
**Foo**
FooId int
FooName varchar(10)
**Bar**
BarId int
FooId int (FK)
BarName varchar(10)
I create a select statement like:
SELECT
FooId,
FooName,
(
SELECT
BarId,
FooId,
BarName
FROM
Bar
WHERE
Bar.FooId = Foo.FooId
AND Bar.BarName = 'SomeBar'
FOR XML PATH('Bar'), TYPE
)
FROM
Foo
WHERE
Foo.FooName = 'SomeFoo'
AND Foo.FooId IN
(
SELECT
Bar.FooId
FROM
Bar
WHERE
Bar.BarName = 'SomeBar'
)
FOR XML PATH('Foo'), TYPE
This works as I expect it and returns the correct results. I realized while developing it I needed to duplicate the filtering clauses in both the sub select and the nested selects in the where clause in order to get the correct results.
I'd like to make sure there isn't a better way to do this. A coworker mentioned using aliases to remove the duplicate clauses but am not sure how that would accomplish anything.
Is this necessary, or is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您只想返回具有 Bar 的 Foos,并且您需要在 XML 中保留 Bar 节点(即联接不起作用,因为它会展平您的 XML),则没有办法大大简化这一过程。 您当然可以将 Bar 查询放入公共表表达式中,但如果这样做,整个事情实际上会变得更长。
Assuming that you only want to return Foos that have a Bar, and that you need the preserve the Bar node in the XML (i.e. a join will not work, since it flattens your XML), there is no way to simplify this by much. You can certainly put the Bar query into a common table expression, but the whole thing actually becomes longer if you do that.