【问题标题】:Select a part of text from the xml从 xml 中选择部分文本
【发布时间】:2014-02-19 00:16:50
【问题描述】:
<Quote xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <error>TLP3: The product has no marked price;</error>
</Quote>

我有一个 xml 存储在表的列中,我使用以下查询来提取一个 xml 元素:

select 
    CONVERT(XML, CONVERT(NVARCHAR(max), Response)).value('(/Quote/error)[1]','nvarchar(max)') as Exception 

表达式的结果是:

 TL43:The product has no marked price.;

我只想选择代码:TL43

然后我想单独选择:The product has no marked price.

有什么办法可以做到吗?

XML 更新

【问题讨论】:

  • 您能否提供有关 xml 格式的更多信息

标签: sql-server xml sql-server-2008 sql-server-2008-r2 sql-server-2012


【解决方案1】:

我不确定您是否在询问使用 TSQL XML 功能的方法,但基本的 SQL 功能就足够了。

为了清楚起见,我使用 CTE,但您可以在没有 CTE 的情况下将它们混为一谈。

我假设您可以转换最终的 ';'在“。”的来源中在你想要的输出中,如果这实际上是一个要求。

DECLARE @Response VARCHAR(MAX) = '<Quote xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<error>TLP3: The product has no marked price;</error>
</Quote>'

;WITH cte AS (
  SELECT CONVERT(XML,@Response).value('(/Quote/error)[1]','nvarchar(max)') as Exception
)
SELECT LEFT(Exception,CHARINDEX(':',Exception)-1) Code
      ,SUBSTRING(Exception,CHARINDEX(':',Exception)+1,LEN(Exception)) Exception
  FROM cte

【讨论】:

    【解决方案2】:
    select substring(CONVERT(XML,CONVERT(NVARCHAR(max),Response )).value('(/Quote/error)[1]','nvarchar(max)'),0,charindex(':', CONVERT(XML,CONVERT(NVARCHAR(max),Response )).value('(/Quote/error)[1]','nvarchar(max)'))) as Excepiton 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      相关资源
      最近更新 更多