简体   繁体   English

在没有CLR或全文的情况下,是否有更好的方法在SQL Server 2008中搜索任意文本?

[英]Is there a better way to search for arbitrary text in SQL Server 2008, without CLR or full-text?

Using SQL Server 2008, without using full-text indexing or CLR integration, is there a better way to search a table column for arbitrary text than the following: 使用SQL Server 2008,而不使用全文本索引或CLR集成,是否有比以下方法更好的方法来搜索表列中的任意文本:

declare @SubString nvarchar(max) = 'Desired substring may contain any special character such as %^_[]'

select * from Items where Name like '%' +

    replace(
    replace(
    replace(
    replace(
    replace(
    replace(
        @SubString
    ,';',';;')
    ,'%',';%')
    ,'[',';[')
    ,']',';]')
    ,'^',';^')
    ,'_',';_')

    + '%' escape ';'

That works, but it seems unnecessarily barbaric. 那行得通,但似乎不必要地野蛮。 Is there any simpler, clearer, or more efficient way, given the above limitations? 鉴于上述限制,是否有任何更简单,更清晰或更有效的方法?

There are no constraints on what the Name column might contain, nor what the SubString we're searching for might contain. 对于“ Name列可能包含的内容,或者我们正在搜索的SubString可能包含的内容,没有任何限制。

The only thing I can think of is to turn your replace(replace(replace... into a user-defined function. Then you could streamline your query into: 我唯一想到的就是将您的replace(replace(replace...转换为用户定义的函数。然后,您可以将查询简化为:

SELECT * FROM Items WHERE Name LIKE CleanMyString(@Substring) escape ';'

It's not exactly "simpler". 这并非完全“简单”。 It's not likely to be any more efficient. 效率可能更高。 But it does clean up the syntax and make it cleaner-looking. 但是它确实清理了语法并使它看起来更清晰。

(You can use charindex for straight string searches such as finding every firstname that contains Ben with: (您可以使用charindex进行直接字符串搜索,例如使用以下命令查找包含Ben的每个名字:

 select * for customers where charindex('Ben', firstname) > 0

or you can create all kinds of powerful pattern searching with patindex: 或者您可以使用patindex创建各种强大的模式搜索:

SELECT PATINDEX ('%[0-9].%[0-9].%[0-9].%','278.2.6.49'); 

which returns the number before the first dot or 0 if there aren't three sets of numbers in the string. 它返回第一个点之前的数字;如果字符串中没有三组数字,则返回0。

For a very good introduction of using patterns (its not regular expressions) in TSQL (from where the above example was copied) please see: https://www.simple-talk.com/sql/t-sql-programming/patindex-workbench/ 有关在TSQL中使用模式(不是正则表达式)的很好的介绍(从上面的示例复制的地方),请参阅: https : //www.simple-talk.com/sql/t-sql-programming/patindex-工作台/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM