SQL Server管理工作室 -
我如何在一段时间内联合?
ParentID是ChildID的内部关系
WHILE EXISTS (SELECT ParentID FROM Table1)
BEGIN
SELECT * FROM FinalTable WHERE FinalTableID = (SELECT c.ChildID FROM Table1 as c WHERE c.ChildID = (SELECT d.ChildID FROM Table1 as d WHERE d.ChildID = @MyCounter))
IF(SELECT e.ParentID FROM Table1 as e WHERE e.ChildID = @MyCounter) IS NULL
BREAK
ELSE
SET @MyCounter = (SELECT d.ParentID FROM Table1 as d WHERE d.ChildID = @MyCounter)
CONTINUE
END
此代码目前导致多个行集合包含不同的结果,是否可以将所有内容合并为完整的结果?
FinalTable
-------------------------------
| ID Name Text ChildID
| 1 1 Foo1 Bar1 1
| 2 2 oof1 Bra1 1
| 3 3 ofo1 Rab1 1
--------------------------------
FinalTable
--------------------
| ID Row2 Row3 ChildID
| 1 8 Foo2 Bar2 2
| 2 9 oof2 Bra2 2
| 3 10 ofo2 Rab2 2
--------------------
FinalTable
--------------------
| ID Name Text ChildID
| 1 14 Foo3 Bar3 3
| 2 17 oof3 Bra3 3
| 3 19 ofo3 Rab3 3
--------------------
通缉结果:
FinalTable
--------------------
| ID Name Text ChildID
| 1 1 Foo1 Bar1 1
| 2 2 oof1 Bra1 1
| 3 3 ofo1 Rab1 1
| 4 8 Foo2 Bar2 2
| 5 9 oof2 Bra2 2
| 6 10 ofo2 Rab2 2
| 7 14 Foo3 Bar3 3
| 8 17 oof3 Bra3 3
| 9 19 ofo3 Rab3 3
--------------------
答案 0 :(得分:3)
您可以使用临时表并附加到
CREATE TABLE #FinalTable () -- should be same structure of FinalTable
WHILE EXISTS (SELECT ParentID FROM Table1)
BEGIN
INSERT INTO #FinalTable
SELECT * FROM FinalTable WHERE FinalTableID = (SELECT c.ChildID FROM Table1 as c WHERE c.ChildID = (SELECT d.ChildID FROM Table1 as d WHERE d.ChildID = @MyCounter))
IF(SELECT e.ParentID FROM Table1 as e WHERE e.ChildID = @MyCounter) IS NULL
BREAK
ELSE
SET @MyCounter = (SELECT d.ParentID FROM Table1 as d WHERE d.ChildID = @MyCounter)
CONTINUE
END