Skip to content
Advertisement

Smart way to write where col1 = x OR col2 = x on ALL the columns in SQL

Suppose I have 100 columns and I want to search for something but I don’t know which column to search.

How can I write a loop that:

SELECT *
FROM table
WHERE col1 = 'x' OR col2 ='x' OR col3 = 'x' OR .... OR col100 = 'x';
```

Advertisement

Answer

If numerous and/or variable columns and performance is NOT an primary concern.

Example

 Select *
  From  YourTable A
  Where charindex('X', (Select A.* for xml raw) )>0

EDIT – To get exact match use quotes in the charindex(‘"X"‘,…)

EDIT – To See what is happening

Select RecordString=(Select A.* for xml raw) 
 From  YourTable A
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement