SQL Server Searching Multiple Columns with Multiple Values SQL

qco9c6ql  于 2024-01-05  发布在  其他
关注(0)|答案(4)|浏览(127)

I know it is posible to serach multiple columns with one value.

I would like to serach 3-4 columns for 4 maybe 5 values

I want to check if any of my choosen columns have a certain value in them.

Example

Column 1 | Column 2 | Column 3 | Column 4 
         |          |          |
Hello    |          |          |            = True
         |          |          |
         | Goodbye  |          |            = True
         |          |  Hello   | Goodbye    = True
         |          |          |
         | Hello    |          |            = True
         |          |          |
         |          |  Goodbye |            = True

In the example I would like SQL to pull the data from all of the lines that have Hello or Goodbye even both in some cases.

Is there a way to do what I want?

q43xntqr

q43xntqr1#

There is one more way...

SELECT *
FROM TableName
WHERE 'Value1' IN (Col1,Col2,Col3...) OR 'Val2' in (Col1,Col2,Col3...) OR ...
txu3uszq

txu3uszq2#

If it's only 3 or 4 columns, the simplest solution would be something like this:

SELECT *
FROM TableName
WHERE Column1 IN('Hello', 'Goodbye')
OR Column2 IN('Hello', 'Goodbye')
OR Column3 IN('Hello', 'Goodbye')
OR Column4 IN('Hello', 'Goodbye')
9rygscc1

9rygscc13#

Forgot to follow with my solution: I needed to join 2 tables and search across the columns. They ****ed up and made the id of t1 a varchar, smh, and some of them had nulls so we needed to check for them lest our results were ****ed (this is why the selected answer wouldn't work for me). You don't need the aliases but if you were going deeper it helps keep things straight.

Use "+" operator to add columns to a WHERE, check for nulls, and caste if you need too.

SELECT *
 FROM Table1 AS t1
 LEFT OUTER JOIN Table2 AS t2 
     ON t1.id = t2.id 
 WHERE( ISNULL(CONVERT(VARCHAR,t1.id),'') +  ISNULL(t1.name,'') +  ISNULL(t1.desc,'') +  ISNULL(t2.company,'')) LIKE '%xbox%'
c2e8gylq

c2e8gylq4#

If you want to use wildcards in your criteria patindex is another option

Sample query

declare @SearchText nvarchar(500) 
set @SearchText = '%Biju _umar%'
declare @colSperator nvarchar(10)
// use any character for contactinating your columns , should handle this 
// in your logic
set @colSeperator = '`~`' 
select * from [ActiveProjects] 
where PATINDEX(@SearchText,CONCAT_WS(@colSeperator,[Name],[CreatedByName])) > 0

the searchText can contains wild card characters , the above query will return the contains like matching 'Biju Kumar' or any character instead on '_' like 'Biju Uumar' from columns [Name] and [Description].

相关问题