在xml查询中如何分隔一行中的所有列名和另一行中的数据

时间:2017-11-09 12:54:37

标签: sql-server xml tsql xpath xquery

  declare @query xml= 
    <emp>
    <eid>1</eid>
    <ename>raju</ename>
    <did>15</did>
    <age>25</age>
    <sal>20000.0000</sal>
    <job>clerk</job>
    <address>hyd</address>
    <gender>male</gender>
    <date>2014-01-01T00:00:00</date>
    </emp>

output:=
    eid     1
    ename   raju
    did     15
    age     25
    sal     20000
    job     clerk
    address hyd
    gender  male
    date    2014-01-01T00:00:00

在xml查询中读取我想要这样

2 个答案:

答案 0 :(得分:1)

在SQL-Server中,这将是这个例子。其他RDMBS需要不同的语法,但您可能会有一个想法:

declare @query xml= 
      N'<emp>
          <eid>1</eid>
          <ename>raju</ename>
          <did>15</did>
          <age>25</age>
          <sal>20000.0000</sal>
          <job>clerk</job>
          <address>hyd</address>
          <gender>male</gender>
          <date>2014-01-01T00:00:00</date>
        </emp>'; 

SELECT @query.value(N'(/emp/eid/text())[1]',N'int') AS eid
      ,@query.value(N'(/emp/ename/text())[1]',N'nvarchar(max)') AS ename

结果

eid ename
1   raju

UPDATE:行中的值

使用xml的.node()读取所有元素(/*)并使用local-name()读取元素的名称:

SELECT nd.value(N'local-name(.)','nvarchar(max)') AS NodeName
      ,nd.value(N'text()[1]','nvarchar(max)') AS NodeValue
FROM @query.nodes(N'/emp/*') AS A(nd)

结果

NodeName    NodeValue
eid         1
ename       raju
did         15
age         25
sal         20000.0000
job         clerk
address     hyd
gender      male
date        2014-01-01T00:00:00

答案 1 :(得分:0)

Drop table #temp -- Drop Table
Go
declare @query xml= 
    '<emp>
    <eid>1</eid>
    <ename>raju</ename>
    <did>15</did>
    <age>25</age>
    <sal>20000.0000</sal>
    <job>clerk</job>
    <address>hyd</address>
    <gender>male</gender>
    <date>2014-01-01T00:00:00</date>
    </emp>'
SELECT *
INTO #temp -- Temp Table
FROM (
SELECT  
   Tbl.Col.value('eid[1]', 'varchar(7)') eid,  
   Tbl.Col.value('ename[1]', 'varchar(7)') ename,  
   Tbl.Col.value('did[1]', 'varchar(7)') did,
   Tbl.Col.value('age[1]', 'varchar(7)') age,
   Tbl.Col.value('sal[1]', 'varchar(7)') sal,
   Tbl.Col.value('job[1]', 'varchar(7)') job,
   Tbl.Col.value('address[1]', 'varchar(7)') address,
   Tbl.Col.value('gender[1]', 'varchar(7)') gender,
   Tbl.Col.value('date[1]', 'varchar(7)') date 
FROM @query.nodes('//emp') Tbl(Col) ) as data


--Select * From #temp
Go
SELECT [Column], data
FROM #temp AS t
UNPIVOT
(
Data
  FOR   [Column] IN(eid, ename, did,age,sal,job,address,gender,date)
) AS u;

--Result
[enter image description here][1]