一种可能的方法是实际删除 FOR XML EXPLICIT 部分并查看由您的 sql 语句生成的结果集。它将指示生成 xml 的嵌套,并希望将您引导至该问题。请参阅以下图片,该图片取自 MSDN 文档:http:
//msdn.microsoft.com/en-us/library/ms189068.aspx。

编辑
发布示例输出可能值得,但在图像中的示例中,如果任何带有 tag=3 的行的 Order!2!Id 为空,您将得到相同的错误。此列实际上是标记 = 2 的父行和标记 = 3 的子行之间的连接。如果您的数据如上所示,我认为您可以通过识别 parent=2 且 Order!2!Id 为空的行来有效地找到您的问题。
或者,它可能是订购。在这种情况下,您可以以某种方式构建一个查询,该查询标识在结果集中出现在 Tag = 2 行之前的任何 Parent = 2 行。
编辑 2
CREATE TABLE MyTable(
Tag int,
Parent int,
SomeIdentifier int
)
INSERT INTO MyTable VALUES (2, 1, 1) -- this row defined before parent
INSERT INTO MyTable VALUES (1, null, 1)
INSERT INTO MyTable VALUES (3, 2, 1)
INSERT INTO MyTable VALUES (3, 2, 1)
INSERT INTO MyTable VALUES (1, null, 2)
INSERT INTO MyTable VALUES (2, 1, 2)
INSERT INTO MyTable VALUES (3, 2, 2)
INSERT INTO MyTable VALUES (3, 2, 2)
INSERT INTO MyTable VALUES (1, null, 3)
INSERT INTO MyTable VALUES (3, 2, 3) -- this is orphaned
INSERT INTO MyTable VALUES (3, 2, 3) -- this is orphaned
;WITH myCte AS(
SELECT Tag
,Parent
,SomeIdentifier
,ROW_NUMBER() OVER (PARTITION BY SomeIdentifier ORDER BY(SELECT 0)) AS RowOrder
FROM MyTable
) SELECT c1.Tag
,c1.Parent
,c1.SomeIdentifier
FROM myCte c1
LEFT OUTER JOIN myCte c2 ON c2.SomeIdentifier = c1.SomeIdentifier AND c1.Parent = c2.Tag
WHERE c1.Parent IS NOT NULL --ignore root rows for now
AND (c1.RowOrder < c2.RowOrder --out of order rows
OR
c2.Tag IS NULL) --orphaned rows