How to query the xml in SQL XML on a SQL Server 2008 database

╄→尐↘猪︶ㄣ 提交于 2019-12-25 01:44:43

问题


I have a SQL Server 2008 database. There is a table called Documents with the following schema:

 Id            int     PK      
 DocumentXml   xml

The xml documents all look something like:

<docroot>
    <name>Some Name</name>
</docroot>

I want to select all the records where the text value of /docroot/name begins with an "S" (case-insenstive).

How do I execute this query with the best performance?


回答1:


Not sure about the performance - but you can do something like this:

SELECT (list of columns)
FROM dbo.Documents
WHERE DocumentXml.value('(/docroot/name)[1]', 'varchar(100)') LIKE 'S%'

If your database collation is case-insensitive, this LIKE operation will be case-insensitive, too.




回答2:


I want to select all the records where the text value of /docroot/name begins with an "S" (case-insenstive).

Use this XPath expression:

/*/name[starts-with(translate(.,'S','s'), 's')]


来源:https://stackoverflow.com/questions/5086619/how-to-query-the-xml-in-sql-xml-on-a-sql-server-2008-database

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