Search all columns of a table for a value?

后端 未结 9 1530
自闭症患者
自闭症患者 2021-01-17 15:36

I\'ve looked for an answer to this, but all I can find is people asking how to search all columns of ALL tables in a database for a value. I just want to search all columns

9条回答
  •  说谎
    说谎 (楼主)
    2021-01-17 16:35

    Cutesie little work-around that involves a bit less copy-paste, since the command can be produced easily using queries.

    Invert the IN operator in a WHERE clause as VALUE IN (as opposed to the more common use case of FIELD IN ).

    SELECT col_1, col_2, ... , col_n 
    FROM 
    WHERE CAST( AS varchar(max)) IN 
       (
       CAST(col_1 AS varchar(max)),
       CAST(col_2 AS varchar(max)),
       ...,
       CAST(col_n AS varchar(max))
       )
    
    
    

    Since varchar is a pretty malleable data type, this becomes pretty foolproof (you can throw ISNULL/NULLIF to modify as needed), and depending on the use case can probably be used across more than one search value.

    A more robust solution, using dynamic execution and PL/SQL would be to write a procedure to dynamically build a view of the target table (via reading e.g. MySQL's information_schema schema, Oracle's SYS schema, etc.), constrained to a where clause containing the input string hard-coded into a series of 'OR'-concatenated/IN clauses for filter conditions.

    提交回复
    热议问题