【问题标题】:sql server partial string searchsql server 部分字符串搜索
【发布时间】:2017-07-13 01:47:16
【问题描述】:

我很确定有人已经提出了这个问题,但我只是不知道如何写。

在我的 SQL Server 数据库中,我正在尝试搜索 field1 包含 abc 但不包含 abc[de] 的记录

因此会找到以下记录

'123abc222'

'abc'

以下记录将找不到

'123abc[de]'

我知道

'abc123abc[de]' 很棘手,但我现在不必担心。

很多人会问我为什么要执行此搜索而不是更改程序、数据库等。这就是问题所在。程序处于稳定状态的问题。添加一个额外的字段几乎是不可能的任务。我们团队想要引入更多问题的最后一件事。是的,添加额外的列或修改数据库设计会更好,但是,就像大多数现实世界的应用程序一样,我们只想对现有应用程序进行最小的更改

谢谢

【问题讨论】:

    标签: sql sql-server regex pattern-matching


    【解决方案1】:

    谢谢大家的回答。我没有正确模拟问题是我的错误

    引用 jce 和 SqlZim

    select * 
    from t 
    where field1 like '%abc%'
      and field1 not like '%\[abcde]%' ESCAPE '\'
    

    感谢大家的帮助

    【讨论】:

      【解决方案2】:

      如何将所有数字替换为空字符,然后使用 '=' 比较器比较结果。

      SELECT *
      FROM table
      WHERE field = REPLACE(REPLACE(REPLACE(REPLACE(
            REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
            REPLACE(@str, '0', ''),'1', ''),'2', ''),
            '3', ''),'4', ''),'5', ''),'6', ''),'7',
            ''),'8', ''),'9', '')
      

      这将只留下字母字符。

      【讨论】:

        【解决方案3】:

        类似:

        select * from table where field like 'abc%' and field not like '%def%';

        【讨论】:

        • 它什么也不检索
        【解决方案4】:
        select * 
        from t 
        where field1 like '%abc%'
          and field1 not like '%abcde%'
        

        测试设置:http://rextester.com/ZZTZ72327

        create table t (
            id int identity(1,1)
          , field1 varchar(32) not null
        );
        insert into t values
         ('123abc222')
        ,('123abcde');
        

        查询:

        select * 
        from t 
        where field1 like '%abc%'
          and field1 not like '%abcde%'
        

        结果:

        +----+-----------+
        | id |  field1   |
        +----+-----------+
        |  1 | 123abc222 |
        +----+-----------+
        

        【讨论】:

        • @user12345 您的where 中是否还有其他使用or 的条件没有正确地用括号括起来?
        • 这就是我要辩论的内容。最坏的情况是最坏的情况,我只需要在 asp.net 上再添加一列和一个控件。这是我最后的选择
        • @user12345 添加了一个 rextester 测试以显示查询检索到正确的结果。
        • 我的道歉。我不想使用真实数据。我用p。原来 [ 是一个转义字符。我本可以使用其他角色。我碰巧用那个。对不起大家。我将对正确答案进行投票。我刚刚用 [.这是转义字符的链接。 stackoverflow.com/questions/5139770/…。感谢大家的帮助
        【解决方案5】:

        使用likenot like

        where col like '%abc%' and col not like '%abcde%'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-28
          • 1970-01-01
          • 2018-01-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多