SQL 显示存储过程的详细信息,其中存储过程的内容使用临时文件中包含的函数名称 table

SQL Show stored procedure details where contents of stored procedure uses a function name contained in a temp table

我有一个包含函数名称列表的临时 table,我想找到所有在存储过程代码中提到这些函数名称之一的存储过程作为查询中的新行结果。

这是我一直在尝试的:

--Gets list of functions and puts them into a new temp table.
Select *
into #functionList
from
(
    SELECT name
      FROM sys.sql_modules m 
    INNER JOIN sys.objects o 
            ON m.object_id=o.object_id
    WHERE type_desc like '%function%'
) as myFunctionList

--The following SQL will get me a list of stored procedures where the contents of the stored procedure
--contains a word I want to look up.
    SELECT DB_NAME() as DB_Name
        ,name AS Procedure_name 
        ,SCHEMA_NAME(schema_id) AS Schema_name
        ,Type_desc
        ,Create_date
        ,Modify_date
    FROM sys.procedures
    WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE "%MyWord%"

最后一步让我感到难过,因为我不想查找“MyWord”,而是想检查临时 table 中的每个结果。我目前正在尝试查看是否可以通过使用子查询来获得它,但我运气不佳。

我设法解决了我的问题,我从 here 中得到了一些启发。

创建 2 个临时 tables,一个用于保存函数名称,另一个用于保存最终查询的结果。

CREATE TABLE #FunctionList
(
     FunctionID INT IDENTITY(1,1) PRIMARY KEY
    ,[Name] NVARCHAR(250) NOT NULL
)

CREATE TABLE #Results
(
     FunctionID INT IDENTITY(1,1) primary key
    ,[DB_Name] NVARCHAR(250) NULL
    ,[Procedure_name] NVARCHAR(250) NULL
    ,[Schema_name] NVARCHAR(250) NULL
    ,[Type_desc] NVARCHAR(250) NULL
    ,[Create_date] DateTime NULL
    ,[Modify_date] DateTime NULL
)

用函数名称填充温度 table。

INSERT INTO #FunctionList([Name])
SELECT [Name]
FROM
(
    SELECT
        [Name]
    FROM sys.sql_modules m 
    INNER JOIN sys.objects o ON m.object_id=o.object_id
    WHERE type_desc LIKE '%function%'
) AS myFunctionList

遍历函数名称 temp table 并查看函数是否正在任何存储过程中使用。如果是,则将结果添加到搜索结果 temp table.

DECLARE @Id INT --For the loop.
DECLARE @functionName NVARCHAR(250) --For the dynamic LIKE.

WHILE (SELECT Count(*) FROM #FunctionList) > 0
BEGIN

    SELECT TOP 1 @Id = FunctionID FROM #FunctionList
    SELECT TOP 1 @functionName = [Name] FROM #FunctionList

    INSERT INTO #Results([DB_Name],[Procedure_name],[Schema_name],[Type_desc],[Create_date],[Modify_date])
    SELECT
         [DB_Name]
        ,[Procedure_name]
        ,[Schema_name]
        ,[Type_desc]
        ,[Create_date]
        ,[Modify_date]
    FROM
    (
        SELECT DB_NAME() AS DB_Name
            ,[Name] AS [Procedure_name] 
            ,SCHEMA_NAME(schema_id) AS [Schema_name]
            ,[Type_desc] AS [Type_desc]
            ,[create_date] AS [create_date]
            ,[Modify_date] AS [Modify_date]
        FROM sys.procedures
        WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%' + @functionName + '%'
    ) AS abc

    Delete #FunctionList Where FunctionID = @Id --Next TOP 1 will be next row in Fn list.

End

瞧!它有效并给了我想要的结果。

就我个人而言,我不是很喜欢我是如何做到这一点的,我之所以这样认为是因为使用 while 循环脚本的性能不佳。如果我能对此脚本提出任何改进性能的建议,我将不胜感激。