SQL Server:从XML列中提取值

时间:2013-11-08 20:11:51

标签: sql sql-server xml

我在SQL Server的表xml中有一个Formdatapt_formdata。这就是我的xml的样子:

<?csps doctype="dataset" version="1.0.0"?> 
<csps:root formtype="AFTeleIntake" guid="ecde2347-ae24-4bd0-a4bd-60e11ca38ed9" xmlns:csps="http://tempuri.org/AFTeleIntake.xsd">
 <Questions>
  <row>
   <ReferringProvider>Abc</ReferringProvider> 
   <PrimaryCareProvider>Bcd</PrimaryCareProvider> 
   <TelephoneContactDate>07-Nov-2013</TelephoneContactDate> 
   <AFType>type1</AFType> 
  </row>
 </Questions>
</csps:root>

我想创建一个SQL查询来从此xml列中获取AFType。我是SQL Server的新手,我尝试了很多功能。

例如:

SELECT 
   PT_FormData.Formdata.query('declare namespace x="http://tempuri.org/AFTeleIntake.xsd";
      (/x:csps/x:Questions/x:row/x:AFType)') AS Description 
FROM database.[dbo].[PT_FormData]

但是输出列是空的。我怎么能绕过我想要的东西?

任何帮助将不胜感激

由于 蒂娜

2 个答案:

答案 0 :(得分:1)

试试这个:

;WITH XMLNAMESPACES('http://tempuri.org/AFTeleIntake.xsd' AS csps)
SELECT
    Formdata.value('(/csps:root/Questions/row/AFType)[1]', 'varchar(50)')
FROM 
  PT_FormData

答案 1 :(得分:0)

以下是如何从上述案例中获取AFType的示例:

DECLARE @x XML
SET @x = '<?csps doctype="dataset" version="1.0.0"?> 
<csps:root formtype="AFTeleIntake" guid="ecde2347-ae24-4bd0-a4bd-60e11ca38ed9" xmlns:csps="http://tempuri.org/AFTeleIntake.xsd">
 <Questions>
  <row>
   <ReferringProvider>Abc</ReferringProvider> 
   <PrimaryCareProvider>Bcd</PrimaryCareProvider> 
   <TelephoneContactDate>07-Nov-2013</TelephoneContactDate> 
   <AFType>type1</AFType> 
  </row>
  <row>
   <ReferringProvider>Abc</ReferringProvider> 
   <PrimaryCareProvider>Bcd</PrimaryCareProvider> 
   <TelephoneContactDate>07-Nov-2013</TelephoneContactDate> 
   <AFType>type2</AFType> 
  </row>
 </Questions>
</csps:root>'


select t.c.value('AFType[1]', 'varchar(50)')
from @x.nodes('declare namespace csps="http://tempuri.org/AFTeleIntake.xsd"; csps:root/Questions/row') t(c)