Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query a SQL field for whether it contains any one of multiple values

I want to query the rows of SQL column for whether it contains any one of multiple values.

For instance, return rows of a table where its column A contains any of the following words: ('cow','farmer','milk').

Easy enough when you know what the words are, but I want to write a sproc where I can feed in any array of strings and if the column A for a certain row contains any of them, it would return the row.

I would want to be able to feed in:

('cow','farmer','milk')

or

('cow','farmer','steak','yikes')

or

('cow','farmer','three', 'pigs', 'wolf')

It must be relatively straightforward, but I cannot for the life of me figure it out. I'm on SQL Server 2008

like image 552
Matt Avatar asked Aug 16 '12 23:08

Matt


People also ask

How do I check if multiple values in one column in SQL?

Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2);

How do I SELECT multiple values in SQL query?

To select multiple values, you can use where clause with OR and IN operator.


2 Answers

One simple approach:

declare @candidates varchar = '|cow|farmer|three|pigs|wolf|'
select * from TableName where @candidates like '%|' + FieldName + '|%'

The best way to do this in SQL 2008 is with a table-valued parameter.

like image 139
Av Pinzur Avatar answered Oct 15 '22 05:10

Av Pinzur


I had the same dilema, and came up with the following. For example, if table_a contains ('My Cow', 'My Goat', 'My Dog') and table_b contains ('Dog', 'Cow'), then...

create table #table_a (field1 varchar(128))
insert into #table_a values('My Cow')
insert into #table_a values('My Goat')
insert into #table_a values('My Dog')

create table #table_b (field1 varchar(128))
insert into #table_b values('Dog')
insert into #table_b values('Cow')

select * from #table_a table_a where (select count(*) from #table_b table_b where charindex(table_b.field1, table_a.field1) > 0) > 0

returns ('My Cow','My Dog')

Hope this helps.

like image 22
raeldor Avatar answered Oct 15 '22 07:10

raeldor