从不同的节点和标签中获取xml数据

时间:2017-04-24 14:16:09

标签: sql-server tsql

我试图在临时表中插入XML数据

DEPARTMENT name="Administration" Revision="" IsRevision="False" Configuration="">
  <FIELD name="Name" value="Jean" type="char" />
  <FIELD name="LastName" value="Dupont" type="char" />
  <FIELD name="EmployeeID" value="5" type="float" />                  
  <ATTACHED_DOCUMENTS>
    <DOCUMENT FileName="contract.pdf" Directory="D:/Contracts"/>
  </ATTACHED_DOCUMENTS>
</DEPARTMENT>  

  insert #t_employee
(t_department,
 t_name,             
 t_value,    
 t_type)     
select *  
 from openxml (@doc, 'DEPARTMENT/FIELD')  
 with (t_department varchar(255) '../@name',
    t_name varchar(255) '@name',     
    t_value varchar(255) '@value',    
    t_type varchar(max) '@type'); 

此代码有效。 但现在我想要的是在我的表中添加一列,并在&#34; Attached_documents&#34;中获取文档的信息。标签

我试图改变这样的路径来添加它但它没有用

select *  
 from openxml (@doc, 'DEPARTMENT)  
 with (t_department varchar(255) '@name',
t_name varchar(255) 'FIELD/@name',     
t_value varchar(255) 'FIELD/@value',    
t_type varchar(max) 'FIELD/@type',
t_document varchar(max) 'ATTACHED_DOCUMENTS/@FileName'); 

如何在表格中插入文档信息?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

由于我无权访问您的XML文档,因此我需要使用变量;希望这足以让您做出必要的更改。

-- your XML doc
DECLARE @doc XML =
'<DEPARTMENT name="Administration" Revision="" IsRevision="False" Configuration="">
  <FIELD name="Name" value="Jean" type="char" />
  <FIELD name="LastName" value="Dupont" type="char" />
  <FIELD name="EmployeeID" value="5" type="float" />                  
  <ATTACHED_DOCUMENTS>
    <DOCUMENT FileName="contract.pdf" Directory="D:/Contracts"/>
  </ATTACHED_DOCUMENTS>
</DEPARTMENT>'

-- Solution    
select 
  DepartmentName = FIELD.value('(../@name)[1]', 'varchar(100)'),
  FieldName      = FIELD.value('(@name)[1]',  'varchar(100)'),
  FieldTxt       = FIELD.value('(@value)[1]', 'varchar(100)'),
  FieldType      = FIELD.value('(@type)[1]', 'varchar(100)'),
  [FileName]     = info.value('(DOCUMENT/@FileName)[1]', 'varchar(100)'),
  FileDirectory  = info.value('(DOCUMENT/@Directory)[1]', 'varchar(100)')
FROM (VALUES (@doc)) t(x)
CROSS APPLY x.nodes('/DEPARTMENT/FIELD') FIELDS(FIELD)
CROSS APPLY (VALUES (@doc.query('(//DOCUMENT)'))) doc(info);

结果

DepartmentName FieldName      FieldTxt       FieldType      FileName       FileDirectory
-------------- -------------- -------------- -------------- -------------- --------------
Administration Name           Jean           char           contract.pdf   D:/Contracts
Administration LastName       Dupont         char           contract.pdf   D:/Contracts
Administration EmployeeID     5              float          contract.pdf   D:/Contracts