SQL Query解析XML并删除数据并将剩余结果发送到多个列

时间:2016-05-25 20:05:37

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

有没有办法从表中的列中解析XML字符串数据,并且能够轻松地使用通配符自动删除部分XML字符串?

示例:



Example: 

<audit><fieldid>id="John"<fieldid>id="bob</audit>  
  
  How would i be able to remove just <fieldid>id="bob?
&#13;
&#13;
&#13;

&#13;
&#13;
How would i be able to remove just <fieldid>id="bob?  

If there are more values after <fieldid>id="bob, how would i be able remove those as well, but keep the </audit> in place at the end.

I have tried the following Update Statement and it did not work with a wildcard:

Update Table
Set column=Replace(Column, '<fieldid>id="bob%', </Audit>
&#13;
&#13;
&#13;

我尝试过以下操作,但替换功能中的通配符不起作用:

更新表 set column = replace(列,&#39; id =&#34; bob%&#39;,

1 个答案:

答案 0 :(得分:1)

假设:

模式id =&#34; bob只会出现一次。

这应该这样做。您只需要将变量@var替换为您的列:

DECLARE @Var VARCHAR(MAX) = '<audit><fieldid>id="John"<fieldid>id="bob</audit>';

SELECT REPLACE(@Var, SUBSTRING(@Var, PATINDEX('%<fieldid>id="bob%', @Var), PATINDEX('%<%', SUBSTRING(@Var, PATINDEX('%<fieldid>id="bob%', @Var)+1, LEN(@Var)))), '');

结果:

enter image description here

回答您的评论&#34;是否可以让脚本删除bob后的所有值并替换为?&#34;

DECLARE @Var VARCHAR(MAX) = '<audit><fieldid>id="John"<fieldid>id="bob<fieldid>id="John"</audit>';

SELECT REPLACE(@Var, SUBSTRING(@Var, PATINDEX('%<fieldid>id="bob%', @Var), PATINDEX('%</audit>%', SUBSTRING(@Var, PATINDEX('%<fieldid>id="bob%', @Var)+1, LEN(@Var)))), '');

结果:

enter image description here