如何从 table 和相对 xml 列创建 select,同时将 XML 列拆分为行?

How to make a select from a table and from relative xml column while splitting into rows the XML column?

我有一个有两列的 table T。 A 列是 varchar 列,B 列是 XML 列。

B 列中的某处始终有以下 parent 标记:<Documents> ... </Documents>。里面还有很多<Document>...</Document>children.

我想要一个包含两列的结果集:

例如开始 table T:

Column A | Column B
--------------------------------------------------------------------------
abc      | <Documents><Document>Doc 1</Document><Document>Doc 2</Document></Documents>

预期结果:

Column 1 | Column 2
-------------------------------------
abc      |<Document>Doc 1</Document>
abc      |<Document>Doc 2</Document>

我可以这样得到第 2 列(如 docs 中所示):

SELECT T2.C.query('.')
FROM T
CROSS APPLY T.[Column B].nodes('*/Documents/*') as T (C)

但这不起作用:

SELECT T.[Column A], T2.C.query('.')
FROM T
CROSS APPLY T.[Column B].nodes('*/Documents/*') as T2 (C)

那么如何得到预期的结果呢?

这是操作方法。

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID CHAR(3), xmldata XML);;
INSERT INTO @tbl (ID, xmldata)
VALUES
('abc', '<Documents><Document>Doc 1</Document><Document>Doc 2</Document></Documents>')
, ('xyz', '<Documents><Document>Doc 10</Document><Document>Doc 20</Document></Documents>');
-- DDL and sample data population, end

SELECT ID
    , c.query('.') AS [Column 2]
FROM @tbl AS tbl
    CROSS APPLY tbl.xmldata.nodes('//Documents/Document') AS t(c);

Output

+-----+-----------------------------+
| ID  |          Column 2           |
+-----+-----------------------------+
| abc | <Document>Doc 1</Document>  |
| abc | <Document>Doc 2</Document>  |
| xyz | <Document>Doc 10</Document> |
| xyz | <Document>Doc 20</Document> |
+-----+-----------------------------+