递归查询中的条件
我在 MS SQL 中有以下递归表值函数,以便从数据库检索对象的层次结构:
WITH tmpField (ParentNum, ChildNum, FieldNum, FieldDescr, Iteration) AS
(
SELECT Field.ParentNum, Field.ChildNum, Field.FieldNum, Field.FieldDescr, 1
FROM Field
WHERE Field.ParentNum = @ParentNum
UNION ALL
SELECT Field.ParentNum, Field.ChildNum, Field.FieldNum, Field.FieldDescr, tmpField.Iteration + 1
FROM Field INNER JOIN
tmpField on Field.ParentNum = tmpField.ChildNum
)
SELECT DISTINCT ParentNum AS ParentNum, ChildNum AS ChildNum, FieldNum, FieldDescr
FROM tmpField
我想按以下方式修改它:
在最后迭代中,当有不再有“孩子”,我希望 ChildNum
字段具有 FieldNum
的值。在之前的所有迭代中,ChildNum
应该具有 ChildNum
字段的值,就像现在一样。
任何人都可以建议一种以上述查询为起点来实现此目的的方法吗?
请注意:尽管有它的名称,字段 ChildNum
并不引用行的任何子项,但它应该被解释为该行的标识符。
I have the following recursive table-valued function in MS SQL, in order to retrieve a hierarchy of objects from the database:
WITH tmpField (ParentNum, ChildNum, FieldNum, FieldDescr, Iteration) AS
(
SELECT Field.ParentNum, Field.ChildNum, Field.FieldNum, Field.FieldDescr, 1
FROM Field
WHERE Field.ParentNum = @ParentNum
UNION ALL
SELECT Field.ParentNum, Field.ChildNum, Field.FieldNum, Field.FieldDescr, tmpField.Iteration + 1
FROM Field INNER JOIN
tmpField on Field.ParentNum = tmpField.ChildNum
)
SELECT DISTINCT ParentNum AS ParentNum, ChildNum AS ChildNum, FieldNum, FieldDescr
FROM tmpField
I want to modify it in the following way:
In the last iteration, when there are no more 'children', I want the ChildNum
field to have the value of FieldNum
. In all previous iterations, ChildNum
should have the value of the ChildNum
field, as it is now.
Can anyone suggest a method to achieve this, using the above query as a starting point?
Please note: despite its name, the field ChildNum
does not reference any children of a row, but it should be interpreted as the identifier of that row.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当没有更多的孩子时,这意味着 ChildNum 为 NULL,所以:
编辑:(遵循 Daan 评论)
好的,在这种情况下,我们可以检查 ChildNum 'children' 计数:
EDIT2:
让我们将检查移到外面:
when there are no more children it means that ChildNum is NULL so:
EDIT: (following Daan comment)
ok, in that case, we could check on ChildNum 'children' count :
EDIT2:
let's move the check outside:
这应该返回您需要的数据。
我删除了迭代,因为您以后不使用它
JOIN VERSION
或
SUBQUERY VERSION (修改为使用 EXISTS 而不是 COUNT)
This should return data you need.
I removed iteration as you don't use it later
JOIN VERSION
or
SUBQUERY VERSION (modified to use EXISTS instead of COUNT)