Wiz*_*Wiz 4 xml t-sql xquery sql-server-2008-r2
我正在使用SQL Server 2008 R2,我的存储过程采用结构化XML,其中包含多个级别,如下所示:
DECLARE @XML xml =
'<Main>
<User id="1">
<Departments isSingle="0">
<Department id="1">Admin</Department>
<Department id="2">HR</Department>
<Department id="3">Development</Department>
</Departments>
</User>
<User id="2">
<Departments isSingle="1">
<Department id="1">Admin</Department>
</Departments>
</User>
</Main>'
Run Code Online (Sandbox Code Playgroud)
从上面的例子我想为具有多个部门的用户获得2列(isSingle ="0"),其中第一列是用户id,第二列是整个<Departments>XML.
我可以使用以下查询获取用户标识但是如何将Departments部分作为XML获取:
SELECT
T.C.value('(../@id)','int') AS UserID
, T.C.value('(../Departments)[1]','nvarchar(max)') AS DepartmentsXML
FROM
@XML.nodes('/Main/User/Departments[@isSingle="0"]') AS T(C)
Run Code Online (Sandbox Code Playgroud)
它不允许我xml用作数据类型代替nvarchar(max)
如果细节不明确,请告诉我,我会尽力改进.任何帮助表示赞赏.
你很接近 - 只需.query('.')用于你的第二栏:
SELECT
T.C.value('(../@id)','int') AS UserID,
T.C.query('.') AS DepartmentsXML
FROM
@XML.nodes('/Main/User/Departments[@isSingle="0"]') AS T(C)
Run Code Online (Sandbox Code Playgroud)
这将返回由.nodes()调用选择的XML片段,作为XML.
| 归档时间: |
|
| 查看次数: |
5339 次 |
| 最近记录: |