Find a value anywhere in a database

前端 未结 18 1224
小蘑菇
小蘑菇 2020-11-22 03:52

Given a #, how do I discover in what table and column it could be found within?

I don\'t care if it\'s fast, it just needs to work.

18条回答
  •  离开以前
    2020-11-22 04:17

    Another way using JOIN and CURSOR:

    USE My_Database;
    
    -- Store results in a local temp table so that.  I'm using a
    -- local temp table so that I can access it in SP_EXECUTESQL.
    create table #tmp (
        tbl nvarchar(max),
        col nvarchar(max),
        val nvarchar(max)   
    );
    
    declare @tbl nvarchar(max);
    declare @col nvarchar(max);
    declare @q nvarchar(max);
    declare @search nvarchar(max) = 'my search key';
    
    -- Create a cursor on all columns in the database
    declare c cursor for
    SELECT tbls.TABLE_NAME, cols.COLUMN_NAME  FROM INFORMATION_SCHEMA.TABLES AS tbls
    JOIN INFORMATION_SCHEMA.COLUMNS AS cols
    ON tbls.TABLE_NAME = cols.TABLE_NAME
    
    -- For each table and column pair, see if the search value exists.
    open c
    fetch next from c into @tbl, @col
    while @@FETCH_STATUS = 0
    begin
        -- Look for the search key in current table column and if found add it to the results.
        SET @q = 'INSERT INTO #tmp SELECT ''' + @tbl + ''', ''' + @col + ''', ' + @col + ' FROM ' + @tbl + ' WHERE ' + @col + ' LIKE ''%' + @search + '%'''
        EXEC SP_EXECUTESQL @q
        fetch next from c into @tbl, @col
    end
    close c
    deallocate c
    
    -- Get results
    select * from #tmp
    
    -- Remove local temp table.
    drop table #tmp
    

提交回复
热议问题