【问题标题】:Query xml data - sample data from Microsoft not working查询 xml 数据 - 来自 Microsoft 的示例数据不起作用
【发布时间】:2020-09-20 10:13:09
【问题描述】:

我正在寻找一种不需要手动编辑文件或复制粘贴内容的解决方案。我正在尝试使用这种方法来查询一个 xml 文档

DECLARE @myDoc xml  
DECLARE @ProdID int  
SET @myDoc = '<Root>  
<ProductDescription ProductID="1" ProductName="Road Bike">  
<Features>  
  <Warranty>1 year parts and labor</Warranty>  
  <Maintenance>3 year parts and labor extended maintenance is available</Maintenance>  
</Features>  
</ProductDescription>  
</Root>'  
  
SET @ProdID =  @myDoc.value('(/Root/ProductDescription/@ProductID)[1]', 'int' )  
SELECT @ProdID

来自https://docs.microsoft.com/en-us/sql/t-sql/xml/value-method-xml-data-type?view=sql-server-ver15#a-using-the-value-method-against-an-xml-type-variable的示例

但是当我尝试使用这个示例数据时,当我想设置变量时它就不起作用了。我的 xml 文件还包含单引号,这就是我选择此示例的原因。

DECLARE @myDoc xml  
DECLARE @ProdID int  
SET @myDoc = '<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
</catalog>'  

来自https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v=vs.85)的样本数据

【问题讨论】:

    标签: sql-server xml tsql


    【解决方案1】:

    您选择的样本数据包含引用'

    ...
    <title>XML Developer's Guide</title>
    ...
    

    这打破了文字字符串的定义。 SQL 引擎认为该字符串在 Developer 之后结束,并且不知道如何处理该字符串的其余部分,并尝试告诉您 2 个错误...

    消息 102 级别 15 状态 1 第 6 行
    's' 附近的语法不正确。

    消息 105 级别 15 状态 1 第 23 行
    字符串' '后面的非闭合引号。

    您可以通过用另一个引号“转义”单引号来解决此问题,如下所示:

    ...
    <title>XML Developer''s Guide</title>
    ...
    

    Fiddle

    【讨论】:

    • 但我不能对我的真实文件执行此操作,即手动更改它们。
    • 我可以搜索和替换。但必须有另一种解决方案
    • 取决于您如何使用“真实文件”填充 XML 变量。请创建一个新问题,显示您如何加载真实文件。
    • 我希望你不要复制粘贴它们...看看this 将整个文件导入一列或this 将 XML 值导入单独的列中。 Another example 最后一个场景。
    • 缺少权限(现在仍然是)不是您最初问题的一部分。这完全改变了问题。有了这些新信息,我建议您联系您的数据库管理员以授予您所需的权限。
    猜你喜欢
    • 2016-07-25
    • 2019-07-29
    • 2016-07-23
    • 1970-01-01
    • 2016-05-26
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多