sql-server - How to exclude commented line/text in finding procedure with Text in SQL Server?
问题描述
I have two procedures as shown below.
Create proc FirstProcdure
As
begin
select * from MyTableA
--select * from MyTableB
end
and
Create proc SecondProcdure
As
begin
select * from MyTableB
--select * from MyTableA
end
Now I want to search procedure with text - MyTableA
. It should only come 'FirstProcdure' in result because in 'SecondProcdure' the
text MyTableA
is commented.
I have tried using below query
Select * from sysobjects where OBJECT_DEFINITION (id) like '%MyTableA%'
Currently it is giving both procedure name in search result.
Sometime we need to change procedure definition quickly & then it is difficult to open find and replace several procedures. So I need to search only procedure name for which the searched text is not the part of commented lines.
解决方案
You can use the custom function for ignore comment text search.
CREATE FUNCTION SearchCommentText(@Value VARCHAR(MAX),@SearchText VARCHAR(MAX))
RETURNS INT
AS
BEGIN
DECLARE @cursor INT = 0,@ret INT=0
declare @commenttext varchar(max)=''
WHILE PATINDEX('%--%', @Value) > 0 OR PATINDEX('%/*%', @Value) > 0
BEGIN
IF CHARINDEX('--', @Value, 0)BETWEEN 1 AND CHARINDEX('/*', @Value, 0)
OR CHARINDEX('/*', @Value, 0) = 0
BEGIN
SET @commenttext=@commenttext+ SUBSTRING( @Value,CHARINDEX('--', @Value), ISNULL(NULLIF(CHARINDEX(CHAR(13) + CHAR(10), @Value, CHARINDEX('--',@Value)), 0), LEN(@Value)) - CHARINDEX('--', @Value) + 2)
SET @Value = STUFF(@Value, CHARINDEX('--', @Value), ISNULL(NULLIF(CHARINDEX(CHAR(13) + CHAR(10), @Value, CHARINDEX('--', @Value)), 0), LEN(@Value)) - CHARINDEX('--', @Value) + 2, '') ;
END ;
ELSE
BEGIN
SET @cursor = -1 ;
WHILE CHARINDEX('/*', @Value, @cursor + 1)BETWEEN 1 AND CHARINDEX('*/', @Value, @cursor + 1)
SET @cursor = CHARINDEX('/*', @Value, @cursor + 1) ;
set @commenttext=@commenttext+SUBSTRING(@Value, @cursor, CHARINDEX('*/', @Value, @cursor) - @cursor + 2);
SET @Value = STUFF(@Value, @cursor, CHARINDEX('*/', @Value, @cursor) - @cursor + 2, '') ;
END ;
END ;
IF(@commenttext LIKE '%'+@SearchText+'%' AND @Value NOT LIKE '%'+@SearchText+'%')
SET @ret=1;
RETURN @ret;
END;
Execute the following query.
SELECT DISTINCT OBJECT_NAME(sc.id) FROM syscomments sc
WHERE TEXT like '%MyTableA%' AND dbo.SearchCommentText(sc.text,'MyTableA') <>1
推荐阅读
- oracle - 自治数据库上的 Oracle 钱包
- angular - 将库项目升级到 Angular 12?
- css - Bootstrap 5表单组,表单行,表单内联不起作用
- python - python将内置关键字分配给变量
- r - 合并 row.names 上的数据框:列以大写字母表示
- sql - 何时创建子类型或仅使用可选属性
- react-native - 如何隐藏反应原生焦点输入边框?
- validation - 如何在 NestJS 中使用 Prisma 和 ValidationPipe?
- c - 除了使用字符串文字之外,还有其他方法可以在 C 中指定或输入 Unicode 代码点吗?
- database - app.blade.php laravel5.4 中未定义的变量