以TSQL LIKE

时间:2017-08-03 15:27:06

标签: sql-server escaping sql-like

我们正在更新我们在数据库中构建ProjectID字段的方式。目前,有PD80400等值可识别特定项目。

有些存储过程可能会在PDXXXXX条款中使用Where格式,例如ProjectID NOT LIKE 'PD%'

  

我需要在我们的数据库中搜索任何包含对PD%的引用的过程/视图/表/函数/等   目前我正在使用以下脚本但是在捕获包含Where ProjectID NOT LIKE 'PD%'的测试过程时遇到问题而没有搜索%PD% .... whcih返回了太多不需要的结果,例如带有{{{{1}的任何内容1}}。

我的剧本:

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 语句,以便捕获上面列出的示例而不会产生额外的结果?

1 个答案:

答案 0 :(得分:1)

您可以通过指定%字符来转义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%'          |                  |      |
+-----------+------------------------------------+------------------+------+