SQL Server SELECT where any column contains 'x'

后端 未结 5 2014
無奈伤痛
無奈伤痛 2020-12-01 05:22

Using SQL Server 2008, say I have a table called testing with 80 columns and I want to find a value called foo.

I can do:

S         


        
5条回答
  •  天命终不由人
    2020-12-01 05:57

    I took the idea from ubaid ashraf's answer, but made it actually work. Just change MyTableName here:

    SELECT STUFF((
        SELECT ', ' + c.name 
        FROM sys.columns  c
        JOIN sys.types AS t ON c.user_type_id=t.user_type_id
        WHERE t.name != 'int'  AND t.name != 'bit' AND t.name !='date' AND t.name !='datetime'
            AND object_id =(SELECT object_id FROM sys.tables WHERE name='MyTableName')
        FOR XML PATH('')),1,2,'')
    

    You could tweak it to your needs and add or remove conditions from the where column (the 't.name != 'int' AND t.name != 'bit' etc. part), e.g. add 't.name != 'uniqueidentifier'' to avoid getting Conversion failed when converting the varchar value 'myvalue' to data type int type of errors..

    Then copy paste the result into this query (otherwise it didn't work):

    SELECT * from MyTableName where 'foo' in (COPY PASTE PREVIOUS QUERY RESULT INTO HERE)
    

提交回复
热议问题