Search code examples
mysqlsqldatabaseinformation-schema

MySQL find column name where it's value match the pattern


How to search the entire database for column name equal to my rule and specific value as well.

Let's say that i want to search for column name like voucher where it's value contain that word value10

So far i can find the column name but i don't know how to match with value as well.

SELECT column_name FROM information_schema.columns 
WHERE TABLE_SCHEMA = 'dbname' AND column_name LIKE '%voucher%'

So the end goal is to find any column name like voucher containing value10 within it's content.


Solution

  • Create a stored procedure to loop through meta data table INFORMATION_SCHEMA to fetch all tables with column_name of choice. Further dynamic SQL is used to scan each of the tables retrieved for columns having the value of choice.

    DDL and DML for setting the data for testing :

    create table TESTA(COLMNA char(255),COLMNC char(255));
    create table TESTB(COLMNA char(255),COLMNB char(255));
    create table TESTC(COLMND char(255),COLMNA char(255));
    
    insert into TESTA values('value0','someothercolmn');
    insert into TESTB values('value0','anothersomeothercolmn');
    insert into TESTB values('value1','Yetanothercolumn');
    

    Test is to search all tables having column_name as COLMNA with value as value0. The procedure will accept column_name and column_Value, hence can be used across the database, just need to pass values as appropriate.

    CREATE PROCEDURE Findtables( colmn_name VARCHAR(64),colmn_value VARCHAR(64) )
    
    BEGIN
    
       DECLARE tablename CHAR(64);
    
       DECLARE c1 CURSOR FOR
         SELECT table_name
         FROM information_Schema
         WHERE column_name = colmn_name;
    
       OPEN c1;
        lable_loop:LOOP
       FETCH c1 INTO tablename;
    
         select tablename;
         SET @sql = CONCAT('SELECT * FROM  ', tablename, ' WHERE ',colmn_name,' = "',colmn_value ,'" ;'); 
    
            PREPARE stmt FROM @sql;
            EXECUTE stmt; 
            DEALLOCATE PREPARE stmt;
    
         END LOOP lable_loop;  
       CLOSE c1;
    
    END; 
    

    Call the stored procedure :

    CALL Findtables('COLMNA','value0');
    

    Output :

    tablename
    TESTA
    COLMNA  COLMNC
    value0  someothercolmn
    tablename
    TESTB
    COLMNA  COLMNB
    value0  anothersomeothercolmn
    tablename
    TESTC
    COLMND  COLMNA
    

    Demonstration of the solution can be found in DBFIDDLE link [https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=4888a6160faf97fb75665832d6610293][1]

    PS : I have to create INFORMATION_SCHEMA table in dbfiddle as metadata tables are not accessible.