使用sql server在XML列中查找字符串

时间:2017-08-02 09:06:30

标签: sql-server xml tsql

  1. 我有一个带有xml列的表。
  2. 我需要在该xml列中搜索其所有节点和值的子字符串。搜索应该不区分大小写
  3. 每行中XML的结构不同
  4. 我使用下面的查询来做到这一点,

    select * from TableName Where Cast(xmlcolumn as varchar(max) ) like '%searchString%'
    

    这适用于短长度的xml行,如果行长度很大,则无法处理这种情况。只搜索了部分数据。

    建议我实现其他一些方法。

1 个答案:

答案 0 :(得分:1)

如果这是一次性任务,那么我将使用exist XML方法:

DECLARE @Table1 TABLE (
    ID INT IDENTITY PRIMARY KEY,
    CommentAsXML XML
)

INSERT  @Table1 (CommentAsXML)
VALUES  (N'<root><item /><item type="Reg">0001</item><item type="Inv">B007</item><item type="Cus">A0001</item><item type="Br">F0001</item></root>')
INSERT  @Table1 (CommentAsXML)
VALUES  (N'<root><item /><item type="Reg">0005</item><parent><child>B007</child></parent><item type="Br">F0005</item></root>')
INSERT  @Table1 (CommentAsXML)
VALUES  (N'<root><item /><item type="Reg">0005</item></root>')

-- Following query is searching for B007 within InnerText of all XML elements:
SELECT  *
FROM    @Table1 t
WHERE   t.CommentAsXML.exist('//*[lower-case(text()[1]) eq "b007"]') = 1

结果:

ID CommentAsXML
-- ------------------------------------------------------------------------------------------------------------------------------
1  <root><item type="Reg">0001</item><item type="Inv">B007</item><item type="Cus">A0001</item><item type="Br">F0001</item></root>
2  <root><item type="Reg">0005</item><parent><child>B007</child></parent><item type="Br">F0005</item></root>

此外,如果您想在XML中搜索某些文本,请访问&#39;然后可以使用XQuery之后的值:

SELECT  *
FROM    @Table1 t
WHERE   t.CommentAsXML.exist('//@*[lower-case(.) eq "reg"]') = 1

注意:在这两种情况下,字符串常量(例如&#34; reg&#34;)应该是较小的情况。