在给定列名称的所有表中搜索特定值

时间:2018-07-15 10:32:01

标签: sql-server ssms

我正在使用SQL Server。我有很多表,我需要找到一个特定的值并返回该值存在于哪个表中。我知道该值位于哪一列中。

我的方法:首先,我使用游标获取所有可以具有该列名称的表。其次,我一步一步地遍历游标,使用Where子句在每个表上执行选择查询以找到值。如果值在该表中,则应打印“在表中找到”。

我需要在循环中放入一个查询,该查询应打印出存在该值的表名。我正在从游标获取表名,我已经具有列名和值,但无法编写动态SQL查询。请帮助我编写动态查询

DECLARE column_cursor CURSOR FOR   
     SELECT t.name AS 'TableName'
     FROM sys.columns c
     JOIN sys.tables t ON c.object_id = t.object_id
     WHERE c.name LIKE '%Agreement_Number%'
     ORDER BY TableName;  

DECLARE  @table_name NVARCHAR(80), @column_value NVARCHAR(30) ; 
//@table_name --> table from the cursor
//@column_value --> the value that I am searching for 

OPEN column_cursor

FETCH NEXT FROM column_cursor INTO @table_name 

WHILE @@FETCH_STATUS = 0  
BEGIN  
    //Not able to put the logic here .
    //I should be able to iterate over each table and check for the column_value and print if its exists in the table or not

    FETCH NEXT FROM column_cursor INTO @column_name, @table_name  
END 

2 个答案:

答案 0 :(得分:0)

您可能会使用sp_msforeachtable

答案 1 :(得分:0)

使用sp_MSforeachtable

DECLARE @AGREEMENT_NUMBER AS VARCHAR(20)
SET @AGREEMENT_NUMBER='00325685'
declare @sql nvarchar(2000)
set @sql = '
    DECLARE @COUNT AS INT
    SELECT @COUNT=COUNT(*) FROM ? WHERE Agreement_Number='''+@AGREEMENT_NUMBER+'''
    IF @COUNT>0
    BEGIN
        PRINT PARSENAME("?",1)+'' => ''+CONVERT(VARCHAR,@COUNT)+'' ROW(S)''
    END
'
EXEC sp_MSforeachtable
@command1=@sql,@whereand='AND O.ID IN (SELECT OBJECT_ID FROM SYS.COLUMNS C WHERE C.NAME=''Agreement_Number'')'