Parsing xml in sql server

十年热恋 提交于 2020-08-26 08:57:00

问题


I have a table with an ntext type column that holds xml. I have tried to apply many examples of how to pull the value for the company's name from the xml for a particular node, but continue to get a syntax error. Below is what I've done, except substituted my select statement for the actual xml output

DECLARE @companyxml xml

    SET @companyxml = 
    '<Home>
      <slideshowImage1>1105</slideshowImage1>
      <slideshowImage2>1106</slideshowImage2>
      <slideshowImage3>1107</slideshowImage3>
      <slideshowImage4>1108</slideshowImage4>
      <slideshowImage5>1109</slideshowImage5>
      <bottomNavImg1>1155</bottomNavImg1>
      <bottomNavImg2>1156</bottomNavImg2>
      <bottomNavImg3>1157</bottomNavImg3>
      <pageTitle>Acme Capital Management |Homepage</pageTitle>
      <metaKeywords><![CDATA[]]></metaKeywords>
      <metaDescription><![CDATA[]]></metaDescription>
      <companyName>Acme Capital Management</companyName>
      <logoImg>1110</logoImg>
      <pageHeader></pageHeader>
    </Home>'

SELECT c.value ('companyName','varchar(1000)') AS companyname 
FROM @companyxml.nodes('/Home') AS c

For some reason, the select c.value statement has a syntax problem that I can't figure out. On hover in SSMS, it says 'cannot find either column "c" or the user-defined function or aggregate "c.value", or the name is ambiguous.'

Any help on the syntax would be greatly appreciated.


回答1:


try this

 DECLARE @companyxml xml

SET @companyxml = 
'<Home>
  <slideshowImage1>1105</slideshowImage1>
  <slideshowImage2>1106</slideshowImage2>
  <slideshowImage3>1107</slideshowImage3>
  <slideshowImage4>1108</slideshowImage4>
  <slideshowImage5>1109</slideshowImage5>
  <bottomNavImg1>1155</bottomNavImg1>
  <bottomNavImg2>1156</bottomNavImg2>
  <bottomNavImg3>1157</bottomNavImg3>
  <pageTitle>Acme Capital Management Homepage</pageTitle>
  <metaKeywords>CDATA</metaKeywords>
  <metaDescription>CDATA</metaDescription>
  <companyName>Acme Capital Management</companyName>
  <logoImg>1110</logoImg>
  <pageHeader></pageHeader>
</Home>'


DECLARE @Result AS varchar(50)

SET @result = @companyxml.value('(/Home/companyName/text())[1]','varchar(50)')

SELECT @result


来源:https://stackoverflow.com/questions/14465015/parsing-xml-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!