1. 程式人生 > >Mysql查詢特定值是哪些表哪些欄位

Mysql查詢特定值是哪些表哪些欄位

摘自網上 

 

-- 查詢整個資料庫中某個特定值所在的表和欄位的方法
# flush tables;

-- 建立表來儲存查詢結果

drop table if exists tmp_table;


CREATE TABLE tmp_table (

  tablename   VARCHAR(1024) null,

  columnname  VARCHAR(1024) null,

  columnvalue VARCHAR(1024) null

);


DROP PROCEDURE IF EXISTS search_value;

DELIMITER $$
-- v1內容值
CREATE PROCEDURE search_value(v1 VARCHAR(1024))
  BEGIN

    DECLARE done INT DEFAULT 0;
    DECLARE m_table VARCHAR(64);
    DECLARE m_column VARCHAR(64);

    -- 查詢資料庫欄位型別為'varchar' 的欄位
    DECLARE m_tables CURSOR
    FOR
      select table_name, column_name
      from information_schema.columns
      where data_type = 'varchar'
      -- 注意修改這裡的 table_schema
      and table_schema = 'table_schema'
    --      and table_name = 'biz_patient_register'
    ;
    declare continue handler for not FOUND set done = 1;

    set @_v = v1;
    open m_tables;
    FETCH m_tables
    INTO m_table, m_column;
    WHILE done != 1 do
      #       insert into tmp_table select m_table as tablename, m_column as columnname, v1 as columnvalue;
      set @m_sql = concat('insert into tmp_table select ''', m_table, ''' as tablename,''', m_column,
                          ''' as columnname,`', m_column, '` as columnvalue from `', m_table, '` where `', m_column,
                          '` = ''%', v1, '%'';');
      -- 編譯sql
      prepare stmt from @m_sql;

      -- 執行sqL
      EXECUTE stmt;
      deallocate prepare stmt;
      #     select m_table, m_column;
      FETCH m_tables
      INTO m_table, m_column;
    END WHILE;

    CLOSE m_tables;
  End $$
DELIMITER ;

-- 儲存過程建立完成
call search_value('152'); -- 執行儲存過程
select *
from tmp_table; -- 查詢儲存過程執行的結果