我正在使用不同版本的SQL Server:SQL Server 2008 R2和SQL Server 2016.
我想在所有存储过程/函数/触发器/视图中搜索特定文本employee_project
。
所以我写了这个查询:
select *
from sys.object so
inner join sys.sql_modules ssm on so.object_id = ssm.object_id
where ssm.definition like '%employee_project%'
以上查询工作正常。
现在我想仅列出特定文本employee_project
出现的行。
例如,假设存储过程ProcessProject
在3条不同的行上具有特定文本employee_project
:
select id from employee_project where name = @proj_name
/* employee_project is validated */
-- employee_project was updated
然后新查询应返回上述3行,以及相关存储过程/函数/触发器/视图的名称。我怎么能这样做?
object_name line
--------------------------------------------------------------------------
ProcessProject select id from employee_project where name = @proj_name
ProcessProject /* employee_project is validated */
ProcessProject -- employee_project was updated
答案 0 :(得分:0)
我怀疑,这是最适合它的工具......您可以将结果转移到表格并引入全文搜索 ......
但你可以试试这个:该函数在给定的搜索字符串中拆分任何字符串输入,并从搜索字符串开始返回片段。
CREATE FUNCTION dbo.StrangeSplitter(@SplitThis NVARCHAR(MAX),@FindThis NVARCHAR(MAX))
RETURNS TABLE
AS
RETURN
WITH Casted AS
(
SELECT CAST('<x>' + REPLACE((SELECT @SplitThis AS [*] FOR XML PATH('')),@FindThis,'</x><x>') + '</x>' AS XML) AS Splitted
)
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS FindIndex
,@FindThis + ' ' + x.value('text()[1]','nvarchar(max)') AS YourFragment
FROM Casted
CROSS APPLY Splitted.nodes('/x') AS A(x)
GO
- 尝试使用单个字符串,但在SELECT
内使用CROSS APPLY
调用此函数时可以使用相同的字符串:
DECLARE @SearchIn NVARCHAR(MAX)=
N'select id from employee_project where name = @proj_name
Some other text
blah blah
/* employee_project is validated */
More blah
-- employee_project was updated
And even more blah!';
DECLARE @SearchFor NVARCHAR(MAX)=N'employee_project';
SELECT * FROM dbo.StrangeSplitter(@SearchIn,@SearchFor)
WHERE FindIndex>1;
Go
DROP FUNCTION dbo.StrangeSplitter;
您可以使用相同的方法逐行返回文本,如果您使用带CHAR(13)+CHAR(10)
的拆分器过滤结果LIKE
。这将返回包含搜索字符串的所有行。
如果您使用的是SQL-Server 2016+,则可以致电STRING_SPLIT()