t-sql : get a single row with parents, children, grandchildren... n children(t-sql :与父母,孩子,孙子...... n 个孩子一起获得一行)
问题描述
我有一个包含 2 列的表格:ID, ParentID
I have a table with 2 columns: ID, ParentID
我想创建一个新表/视图,每一行都包含所有级别的所有孩子到某个父母...
i want to make a new table/view that each row includes all the children in all levels to a certain parents...
例如:
ParentID Level_1 Level_2 Level_3 ... Level_n
这意味着 parentID 是 Level_1 的父级,它是 level_3 的父级 2 的父级,依此类推...
it means that parentID is the parent of Level_1 which is the Parent of level 2 which is the parent of level_3 and so on...
我需要做没有递归所以没有机会堆栈溢出...
i need to do it with no recursion so no chance to stack overflow...
在 T-SQL 中有一个名为 @@rowcount 的函数,它返回我在最后一次选择中得到的行,所以也许我可以在 while 循环或其他东西中使用它...
in T-SQL there's a function called @@rowcount which returns the rows i got in the last select so maybe i can use it inside a while loop or something...
问题是我怎么知道一开始要构造多少列?知道如何参加这个挑战吗?
the question is how can i know how many columns to construct at the beginning ? any idea how to access this challenge ?
推荐答案
你想要得到的是一个数据透视表,但在我看来,这个任务不属于数据库.我宁愿得到一个包含行的结果集并从外部"旋转它们.
What you're trying to get is a pivot table, but, in my opinion, this task doesn't belong to the database. I'd rather get a result set with rows and pivot them "externally".
为了实现我所描述的,在 SQL Server 2005+ 中,您可以使用公共表表达式 (在这里你可以找到一个例子,而 SQL Server 2000 需要一个稍微不同的方法.
To achieve what I described, in SQL Server 2005+ you can use a Common Table Expression (here you can find an example, while SQL Server 2000 requires a slightly different approach.
注意:虽然你写了没有递归所以没有机会堆栈溢出",你仍然需要保护自己免受无限循环的影响.我个人使用递归并为其建立最大深度";当递归尝试比限制更深"时,我停止它并返回错误.
Note: although you wrote "no recursion so no chance to stack overflow", you'll still have to proect yourself from infinite loops. I personally use recursion and establish a maximum "depth" for it; when the recursion attempts to go "deeper" than the limit, I stop it and return an error.
这篇关于t-sql :与父母,孩子,孙子...... n 个孩子一起获得一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:t-sql :与父母,孩子,孙子...... n 个孩子一起获得
基础教程推荐
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 在多列上分布任意行 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
