获取显示当前xml节点内部的值

时间:2015-02-10 12:45:20

标签: sql sql-server xml tsql

所以这是我遇到的问题,我希望这是有道理的。我编写了一个sql脚本,使用 for xml path 将表中的数据导出到一个xml文件中。

以下是一个示例(您应该只能复制,粘贴并运行以下脚本):

    create table #temptable(
    mykey nvarchar(200),
    myarea nvarchar(200),
    mytype nvarchar(200),
    myvalue nvarchar(max)
    )

    insert into #temptable values ('6385465665245', 'area1', 'type1', 'This area should be inside the keyareatypes node and NOT in the value node.')
    insert into #temptable values ('6632525685488', 'area2', 'type2', 'This area should be inside the keyareatypes node and NOT in the value node.')

    select
    tmp.mykey as '@key',
    tmp.myarea as '@area',
    tmp.mytype as '@type',
    tmp.myvalue as 'value'

    from
    #temptable tmp

    for xml path('keyareatypes'), type

    IF OBJECT_ID('tempdb..#temptable') IS NOT NULL
        DROP TABLE #temptable

如果我运行上述查询,我​​会得到以下内容:

<keyareatypes key="6385465665245" area="area1" type="type1">
    <value>This area should be inside the keyareatypes node and NOT in the value node.</value>
</keyareatypes>
<keyareatypes key="6632525685488" area="area2" type="type2">
    <value>This area should be inside the keyareatypes node and NOT in the value node.</value>
</keyareatypes>

如您所见,<keyareatypes>节点中有另一个名为<value>的节点。我不希望那里有<value>个节点。

非常感谢任何帮助。

感谢。

1 个答案:

答案 0 :(得分:1)

我认为这给出了正确答案:

create table #temptable(
mykey nvarchar(200),
myarea nvarchar(200),
mytype nvarchar(200),
myvalue nvarchar(max)
)

insert into #temptable values ('6385465665245', 'area1', 'type1', 'This area should be inside the keyareatypes node and NOT in the value node.')
insert into #temptable values ('6632525685488', 'area2', 'type2', 'This area should be inside the keyareatypes node and NOT in the value node.')

select
mykey as 'keyareatypes/@key',
myarea as 'keyareatypes/@area',
mytype as 'keyareatypes/@type',
myvalue as keyareatypes
from
#temptable as keyareatypes
for xml path(''),TYPE

IF OBJECT_ID('tempdb..#temptable') IS NOT NULL
    DROP TABLE #temptable

返回

<keyareatypes key="6385465665245" area="area1" type="type1">
  This area should be inside the keyareatypes node and NOT in the value node.
</keyareatypes>
<keyareatypes key="6632525685488" area="area2" type="type2">
  This area should be inside the keyareatypes node and NOT in the value node.
</keyareatypes>