John Shedletsky
John Shedletsky

Reputation: 7178

Using 'LIKE' with an 'IN' clause full of strings

I want to do a soft string match in a table, like this:

SELECT * FROM emailaddresses where addr in ('[email protected]', '[email protected]')

But if there is an addr value in the table '[email protected]', I want that returned.

Sort of like this:

SELECT * FROM emailaddresses where addr LIKE in ('[email protected]', '[email protected]')

How do I do that?

Upvotes: 8

Views: 39060

Answers (6)

Deepak Tekchandani
Deepak Tekchandani

Reputation: 518

We can use the 'LIKE-In' approach together in SQL but in somewhat different style, like the one below:

SELECT * 
FROM emailaddresses 
WHERE addr LIKE '[email protected]' OR addr LIKE '[email protected]'

Upvotes: 1

Prakash Singh
Prakash Singh

Reputation: 1

select * from HotelAmenities_ 
where Pamenities in (
            select distinct(pamenities) 
            from HotelAmenities_ 
            where pamenities like '%Swimming%'
        )

Upvotes: 0

artofsql
artofsql

Reputation: 613

Try this using a cross join to a table containing a list of email's you want to search for:

declare @email table(
email_check nvarchar(500) not null)

insert into @email(email_check)
values('[email protected]')
insert into @email(email_check)
values('[email protected]')



select hit, ID, EMAIL_ADDRESS from (
    select CHARINDEX(email_check, lower(EMAIL_ADDRESS)) hit, ID, EMAIL_ADDRESS
    from Table_With_Email_Addresses
    ,@email
) t
where hit > 0

No need for a "like" since it will parse a string to find a match. Cheers!

Upvotes: 0

Cade Roux
Cade Roux

Reputation: 89741

Note that LIKE will work either case-sensitively or case-insensitively depending upon which collation is in effect for the expression, but in your case, you have specified no wildcards so there is little point looking to use LIKE.

The default SQL Server installation is case-insensitive.

If you want a case-insensitive compare because you've got a case-sensitive database, you can cast. I believe this is the appropriate syntax (I've never used it for an IN list on one side of an expression, though).

SELECT *
FROM emailaddresses
WHERE addr COLLATE SQL_Latin1_General_CP1_CI_AS 
IN (
    '[email protected]' COLLATE SQL_Latin1_General_CP1_CI_AS
    ,'[email protected]' COLLATE SQL_Latin1_General_CP1_CI_AS
)

A real case for LIKE would be something for something like addr LIKE '%@google.com"

Upvotes: 1

Abe Miessler
Abe Miessler

Reputation: 85126

put the values into a table and use a join rather than an in clause:

SELECT * FROM emailaddresses as ea
INNER JOIN addresses as a
ON ea.address like '%' + a.address + '%'

Upvotes: 12

Mike Lewis
Mike Lewis

Reputation: 64177

You can use the LOWER function

SELECT * FROM emailaddresses where LOWER(addr) in ('[email protected]', '[email protected]')

Which will convert all addr to lowercase, in which you can then compare the results to what you want.

Upvotes: 2

Related Questions