代码之家  ›  专栏  ›  技术社区  ›  gruff

类TSQL中的转义单引号和通配符

  •  1
  • gruff  · 技术社区  · 7 年前

    ProjectID PD80400 它标识了一个特定的项目。

    可能存在使用 PDXXXXX Where 条款,例如 ProjectID NOT LIKE 'PD%'

    PD% 目前,我正在使用以下脚本,但在捕获包含 Where ProjectID NOT LIKE 'PD%' 无需搜索 %PD% Update, Updated, etc

    我的脚本:

    SELECT DISTINCT a.[name], b.[text], CASE WHEN a.type IN ('FN', 'TF') THEN 'Function' WHEN a.type = 'P' THEN 'Stored Procedure' WHEN a.type = 'V' THEN 'View'  ELSE 'Unknown' END AS 'ObjectType', a.type
    FROM sysobjects a
    INNER JOIN syscomments b on a.id = b.id
    WHERE b.[text] LIKE '%PD%' AND a.name = 'AAAAAAAAAAAAA_TBG_MM_TestProcedure_PDSearch'--AND b.[text] NOT LIKE 'update%' AND b.[text] NOT LIKE 'EmpD%' AND b.[text] NOT LIKE 'updated' AND a.name NOT LIKE 'Z_OLD%' AND a.name NOT LIKE 'ZOLD%'
    ORDER BY ObjectType
    

    我应该如何格式化 LIKE 声明,以捕捉像我上面列出的例子没有所有额外的结果?

    1 回复  |  直到 7 年前
        1
  •  1
  •   SqlZim    7 年前

    你可以逃离 % 通过指定 escape

    select 
        a.[name]
      , b.[text]
      , case when a.type in ('fn', 'tf') then 'Function' 
             when a.type = 'P' then 'Stored Procedure' 
             when a.type = 'V' then 'View'  
             else 'Unknown' end as 'ObjectType', a.type
    from sysobjects a
      inner join syscomments b on a.id = b.id
    where b.[text] like '%''PD\%%' escape '\'
    order by ObjectType
    

    create procedure dbo.pd_search as 
    select * from master..spt_values 
    where number = 1
      and name not like 'PD%'
    go
    create procedure dbo.pd_search_other as 
    select * from master..spt_values 
    where number = 1
      and name <> 'PD'
    go
    

    rextester演示: http://rextester.com/KPC17170

    返回:

    +-----------+------------------------------------+------------------+------+
    |   name    |                text                |    ObjectType    | type |
    +-----------+------------------------------------+------------------+------+
    | pd_search | create procedure dbo.pd_search as  | Stored Procedure | P    |
    |           | select * from master..spt_values   |                  |      |
    |           | where number = 1                   |                  |      |
    |           |   and name not like 'PD%'          |                  |      |
    +-----------+------------------------------------+------------------+------+