如何查找单个存储过程中是否存在表名列表?

时间:2018-10-19 20:44:41

标签: sql-server tsql stored-procedures

我有一个临时表,其中有2列,一个临时表列出了数据库中的所有表名,另一列则显示了该表是否存在于一个存储过程中。我想循环存储过程中的表名列表,看看它们是否存在。如果存在,我将使用“是”更新临时表中的第二列。

有可能吗?

到目前为止,这是我所拥有的,但是当我运行它时,结果表明,如果不正确,则存储过程中不存在列表中的表名。

DECLARE @TableName VARCHAR(50)

CREATE TABLE #TablesList 
(
     TableName VARCHAR(50), 
     TableExists VARCHAR(3)
)

INSERT INTO #TablesList (TableName)
    SELECT TABLE_NAME
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='DB_Name'
    ORDER BY TABLE_NAME

DECLARE TableNames_Cursor Insensitive CURSOR FOR
    SELECT TableName        
    FROM #TablesList

OPEN TableNames_Cursor

FETCH NEXT FROM TableNames_Cursor INTO @TableName

-- read the cursor rows, and process accordingly -----------------------------------------
WHILE (@@Fetch_Status) = 0 
BEGIN
    --Update #TablesList
    --Set TableExists = 'Yes'
    -- where 
    SELECT
        obj.TableName
    FROM
        (SELECT tl.TableName
         FROM sysobjects obj
         JOIN syscomments com ON com.id = obj.id
         JOIN #TablesList tl ON tl.TableName = @TableName
         WHERE obj.name = 'sProc_Name'
           AND com.text LIKE '%' + @TableName + '%') obj
    ORDER BY 
        obj.TableName       

    FETCH NEXT FROM TableNames_Cursor INTO @TableName
END  -- WHILE (@@Fetch_Status) = 0 

DEALLOCATE TableNames_Cursor

DROP TABLE #TablesList

2 个答案:

答案 0 :(得分:2)

您找到了一个可行的解决方案,可以避免使用游标,但是应该避免使用已弃用的sysobjectssyscomments目录视图,这是很好的。

下面是一个使用较新的目录视图以及一些其他增强功能的示例。不需要临时表,除非稍后将其用于返回结果以外的目的。

SELECT 
      sch.Name AS TableSchemaName
    , tbl.Name AS TableName
    , CASE WHEN EXISTS (
        SELECT 1
        FROM sys.objects AS obj
        JOIN sys.sql_modules AS com on com.object_id = obj.object_id
        WHERE
            obj.name = 'storedProc_Name'
            AND com.definition LIKE '%'+ tbl.name +'%')
      THEN 'Yes' ELSE 'No' END AS TableUsed
FROM sys.tables AS tbl
JOIN sys.schemas AS sch ON sch.schema_id = tbl.schema_id
WHERE tbl.name NOT LIKE 'MLS%';

答案 1 :(得分:1)

我能够编写一个更简单的有效查询

select 
tbl.Name,
isnull((Select top 1
  'Yes'
  From
    sysobjects obj
    join syscomments com on com.id = obj.id
  Where obj.name = 'storedProc_Name'
  and com.Text Like '%'+ tbl.name +'%'), 'No') as Used
  into #TblsUsed
from sys.tables tbl
where tbl.name not like 'MLS%'

select *
from #TblsUsed
where #TblsUsed.Used = 'Yes'
order by #TblsUsed.name