Find a value anywhere in a database

前端 未结 18 904
小蘑菇
小蘑菇 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:09

    I was looking for a just a numeric value = 6.84 - using the other answers here I was able to limit my search to this

    Declare @sourceTable Table(id INT NOT NULL IDENTITY PRIMARY KEY, table_name varchar(1000), column_name varchar(1000))
    Declare @resultsTable Table(id INT NOT NULL IDENTITY PRIMARY KEY, table_name varchar(1000))
    
    Insert into @sourceTable(table_name, column_name)
    select schema_name(t.schema_id) + '.' + t.name as[table], c.name as column_name
    from sys.columns c
    join sys.tables t
    on t.object_id = c.object_id
    where type_name(user_type_id) in ('decimal', 'numeric', 'smallmoney', 'money', 'float', 'real')
    order by[table], c.column_id;
    
    DECLARE db_cursor CURSOR FOR
    Select table_name, column_name from @sourceTable
    DECLARE @mytablename VARCHAR(1000);
    DECLARE @mycolumnname VARCHAR(1000);
    
    OPEN db_cursor;
    FETCH NEXT FROM db_cursor INTO @mytablename, @mycolumnname
    
    WHILE @ @FETCH_STATUS = 0
    BEGIN
        Insert into @ResultsTable(table_name)
        EXEC('SELECT ''' + @mytablename + '.' + @mycolumnname + '''  FROM ' + @mytablename + ' (NOLOCK) ' +
        ' WHERE ' + @mycolumnname + '=6.84')
        FETCH NEXT FROM db_cursor INTO @mytablename, @mycolumnname  
    END;
    CLOSE db_cursor;
    DEALLOCATE db_cursor;
    Select Distinct(table_name) from @ResultsTable
    

提交回复
热议问题