如何使用“nolock”查找存储过程中使用的表列表?

时间:2015-06-15 10:43:12

标签: sql sql-server

我有超过1000个存储过程,由于一些肮脏的程序员,他们会使用'nolock'来存储过程表。

现在,由于日常基础知识中的这个问题,我面临很多问题。

由于某些原因,我无法从SP中删除所有nolock关键字,但我需要知道它发生在哪个存储过程中。

示例:

让我们考虑一个存储过程(sp_user)使用两个表(tbl_salary)和(tbl_account),如果一个表(tbl_account)以{{结尾1}}然后我需要返回以下细节。

(NOLOCK)

任何帮助都会让我非常感激......

2 个答案:

答案 0 :(得分:1)

以下查询可以根据您的需要直接在您的sql server中使用

;WITH stored_procedures AS ( 
    SELECT o.name AS proc_name, oo.name AS table_name, ROW_NUMBER() OVER (partition by o.name,oo.name ORDER BY o.name,oo.name) AS row 
    FROM sysdepends d INNER JOIN sysobjects o ON o.id=d.id INNER JOIN sysobjects oo ON oo.id=d.depid WHERE o.xtype = 'P'
) 
SELECT proc_name, table_name 
FROM stored_procedures 
WHERE row = 1 and proc_name in (
        select specific_name 
        from information_schema.routines 
        where routine_definition like  N'%nolock%'
    ) 
ORDER BY proc_name,table_name

答案 1 :(得分:0)

尝试以下简单查询。这将为所有SP,函数和视图提供" NoLock"无论采用哪种方式,都在使用。

SELECT DISTINCT o.name AS Object_Name,o.type_desc
    FROM sys.sql_modules m 
    INNER JOIN sys.objects o 
    ON m.object_id=o.object_id
    WHERE m.definition Like '%nolock%'

仅针对存储过程

SELECT DISTINCT o.name AS Object_Name
FROM sys.sql_modules m 
INNER JOIN sys.objects o 
ON m.object_id=o.object_id
WHERE m.definition Like '%nolock%' and o.type = 'P'

我已经解决过这个问题并提供解决方案。请尝试:

;WITH stored_procedures AS (
SELECT 
o.name AS proc_name, oo.name AS table_name,
ROW_NUMBER() OVER(partition by o.name,oo.name ORDER BY o.name,oo.name) AS row
FROM sysdepends d 
INNER JOIN sys.objects o ON o.object_id=d.id
INNER JOIN sys.objects oo ON oo.object_id=d.depid AND oo.type = 'U'
INNER JOIN sys.sql_modules m ON m.object_id=o.object_id
INNER JOIN sys.sql_modules mod ON o.object_id = mod.object_id
WHERE o.type = 'P' AND o.Is_MS_Shipped = 0 
AND m.definition Like '%nolock%')
SELECT proc_name, table_name FROM stored_procedures
WHERE row = 1
ORDER BY proc_name,table_name