Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show table name where a value is present

Tags:

database

mysql

Is it possible to show the name of a table in a db where a specific value is present. I have different tables and i want to show only the table names that contains a specific value in any of the fields.

like image 366
SebastianOpperman Avatar asked Oct 13 '11 06:10

SebastianOpperman


1 Answers

This will return lots of empty result sets, but the non-empty ones correspond to table/column combinations that fit your search. It only works for text, and detects columns that contain the value (as opposed to a full column match.)

DELIMITER |

DROP PROCEDURE IF EXISTS `SearchAllTables`|
CREATE PROCEDURE `SearchAllTables` (
    IN _search varchar(256)
    )
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY DEFINER
BEGIN
    -- declare stuff
    declare _tableName varchar(64);
    declare _columnName varchar(64);
    declare _done tinyint(1) default 0;

    -- we will examine every string column in the database
    declare _columnCursor cursor for
        select TABLE_NAME, COLUMN_NAME
            from INFORMATION_SCHEMA.COLUMNS
        where TABLE_SCHEMA = database()
        and (DATA_TYPE like '%char%' 
            or DATA_TYPE like 'text');
    declare CONTINUE handler for NOT FOUND
        SET _done = 1;

    OPEN _columnCursor;
    LOOP1: LOOP
            -- get the next table/column combination
        FETCH _columnCursor INTO _tableName,_columnName;
        IF _done = 1 THEN
            CLOSE _columnCursor;
            LEAVE LOOP1;
        END IF;

            -- query the current column to see if it holds the value
        SET @query = concat(
            "select '",_tableName,"' as TableName, '",
                      _columnName,"' as ColumnName 
            from ",_tableName," 
            where ",_columnName," like concat('%',?,'%') 
            group by 1;"
        );
        SET @search = _search;
        PREPARE _stmt FROM @query;
        EXECUTE _stmt USING @search;
        DEALLOCATE PREPARE _stmt;
    END LOOP LOOP1;
END|

DELIMITER ;

Oh, yeah, and it's ugly... Maybe it'll help you, though!

like image 63
grossvogel Avatar answered Oct 20 '22 04:10

grossvogel