Search code examples
sqlsql-servert-sqlsql-like

SQL Server: display whole column only if substring found


Working with SQL Sever 2016. I am constrained by the fact we cannot create functions or stored procedures. I am trying to find %word% in many columns across a table (75). Right now, I have a very large clump of

and (fieldname1 like %word%
     or fieldname2 like %word%
     or fieldname3 like %word%) etc. 

While cumbersome, this does provide me the correct results. However:

  1. I am looking to simplify this and
  2. in the select, I want to display the whole column if and only if it finds %word% (or even just the column name would work)

Thank you in advance for any thoughts.


Solution

  • --...slow...
    declare @searchfor varchar(100) = '23';
    
    select @searchfor as [thevalue], 
        thexml.query('for $a in (/*[contains(upper-case(.), upper-case(sql:variable("@searchfor")))]) 
        return concat(local-name($a[1]), ",")').value('.', 'nvarchar(max)') as [appears_in_columns],
        *
    from
    (
    select *, (select o.* for xml path(''), type) as thexml
    from sys.all_objects as o --table goes here
    ) as src
    where thexml.exist('/*[contains(upper-case(.), upper-case(sql:variable("@searchfor")))]') = 1;