我正在尝试从 SQL 表中选择值作为具有特定格式的 XML 表。
使用下表...
SELECT x.*
INTO #t
FROM (VALUES (1, 'John', 'Doe')) x(Id, FirstName, LastName)
SELECT *
FROM #t
DROP TABLE #t
我需要一个类似这样的 XML 输出...
<Table>
<Row>
<Column>Id</Column>
<Column>FirstName</Column>
<Column>LastName</Column>
</Row>
<Row>
<Column>1</Column>
<Column>John</Column>
<Column>Doe</Column>
</Row>
</Table>
我能够使用 UNION 和 XML PATH 获得与此匹配的输出...
SELECT t1.*
INTO #t
FROM (VALUES (1, 'John', 'Doe')) t1(Id, FirstName, LastName);
WITH t2(xmlTable) AS (
SELECT t3.Id 'Column'
,''
,t3.FirstName 'Column'
,''
,t3.LastName 'Column'
FROM (
SELECT *
FROM (VALUES ('Id', 'FirstName', 'LastName')) t4(Id, FirstName, LastName)
UNION ALL
SELECT CONVERT(varchar(15), #t.Id)
,CONVERT(varchar(15), #t.FirstName)
,CONVERT(varchar(15), #t.LastName)
FROM #t) t3
FOR XML PATH ('Row'), ROOT('Table'))
SELECT t2.xmlTable
FROM t2
DROP TABLE #t
但这看起来非常麻烦。有没有更优雅的解决方案?具体来说,我可以在没有 UNION 的情况下执行此操作,也许只使用 XML PATH 吗?
请尝试以下使用 SQL Server 的 XQuery 的解决方案。
无论有多少列表格,它都是通用的
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, FirstName VARCHAR(30), LastName VARCHAR(30));
INSERT INTO @tbl (FirstName, LastName) VALUES
('John', 'Doe'),
('Mary', 'Pollack');
-- DDL and sample data population, end
SELECT (
SELECT * FROM @tbl
FOR XML PATH('r'), TYPE, ROOT('root')
).query('<Table><Row>{
for $x in /root/r[1]/*
return <Column>{local-name($x)}</Column>
}</Row>{
for $x in /root/r
return <Row>{
for $y in $x/*
return <Column>{data($y)}</Column>}</Row>
}
</Table>');
输出
<Table>
<Row>
<Column>id</Column>
<Column>FirstName</Column>
<Column>LastName</Column>
</Row>
<Row>
<Column>1</Column>
<Column>John</Column>
<Column>Doe</Column>
</Row>
<Row>
<Column>2</Column>
<Column>Mary</Column>
<Column>Pollack</Column>
</Row>
</Table>