2017-08-03 39 views
1

我們正在對數據庫中構建ProjectID字段的方式進行更新。目前存在諸如PD80400的值,其識別特定項目。在TSQL中使用單引號和通配符LIKE

有可能保存其使用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

您可以通過指定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%'   |     |  | 
+-----------+------------------------------------+------------------+------+ 
+0

好極了!非常感謝,這比我希望的效果更好 – gruff

+0

@gruff高興地幫忙! – SqlZim

相關問題