SQL Using Like, One Variable, Multiple Columns - sql

--where 'email#aol.com' in(o.SuOrderEmailAddress, o.SuBusEmailAddress, o.SuReturnEmail, O.SuPartsEmail) and es.ictid = 7
I want to search one variable (email address) in the multiple columns. This is what I have now, and it works.
I think I need to use Like, because I want to use wildcards. For instance, being able to use *#aol.com would be very helpful. Right now I have to enter an exact email address.
--Where s.suname like 'rizt%'and es.ictid = 7
It was simple enough in this above example, but once I rearrange the syntax to do multiple columns Im lost as to where I can use LIKE so that I can use Wildcards.
Thanks

You could just look at the end of the email address. Most databases support the right() function:
where '#aol.com' in (right(o.SuOrderEmailAddress, 8),
right(o.SuBusEmailAddress, 8),
right(o.SuReturnEmail, 8),
right(o.SuPartsEmail, 8)
) and
es.ictid = 7
(Even databases that don't have right() have an equivalent function, in general.)
Some databases support regular expressions, which is another option. Or, in your case, string concatenation would even work.
EDIT:
If you have a variable, you can do:
where #var in (right(o.SuOrderEmailAddress, len(#var)),
right(o.SuBusEmailAddress, len(#var)),
right(o.SuReturnEmail, len(#var)),
right(o.SuPartsEmail, len(#var))
) and
es.ictid = 7

This is the general idea. Usually, #search would be a parameter to a stored proc. Look at the WHERE clause first.
declare #search varchar(50) = '#aol.com'
set #search = '%' + #search + '%'
select case when o.SuOrderEmailAddress like #search then o.SuOrderEmailAddress
when o.SuBusEmailAddress like #search then o.SuBusEmailAddress
when o.SuReturnEmail like #search then o.SuReturnEmail
when o.SuPartsEmail like #search end as matchedEmail
from MyTable as o
where (o.SuOrderEmailAddress like #search
or o.SuBusEmailAddress like #search
or o.SuReturnEmail like #search
or o.SuPartsEmail like #search) and ...
You could control the adding of '%'s on the front end. This seems to me to be written clearly for the reader and gives you back the email address that was the match.

I think that the real answer is to use Full Text Indexing (if you are using MS SQL - otherwise seeing if there is an equivalent for whatever server you are using). However, here is an ugly hack that should work:
WHERE ISNULL(o.SuOrderEmailAddress, '') + '|'
+ ISNULL(o.SuBusEmailAddress, '') + '|'
+ ISNULL(o.SuReturnEmail, '') + '|'
+ ISNULL(O.SuPartsEmail, '') LIKE #pattern
This simply concatenates all of the relevant fields into a pipe-delimited list before checking that concatenated string for the #pattern.

Related

SQL Server check if value is substring inside isnull

I have a field in UI interface that passes to a stored procedure a null value (when field is unfilled) or a contract number when it is filled. Substrings of the contract number are accepted as input.
Inside the procedure, I need to filter the results by this parameter.
I need something similar to this:
SELECT * FROM tableName tn
WHERE
tn.ContractNumber LIKE ISNULL('%' + #contractNumber + '%', tn.ContractNumber)
What do you think it is the best approach? Problem is that using a condition like this does not return values.
Simply:
SELECT *
FROM tableName tn
WHERE tn.ContractNumber LIKE '%' + #contractNumber + '%'
OR #contractNumber IS NULL
You are really checking multiple condition, so having them separated reads more intuitive (for most people, anyway).
I assume this is just a sample query, and you are not selecting * in reality...
Another one:
SELECT *
FROM tableName tn
WHERE tn.ContractNumber LIKE '%' + ISNULL(#contractNumber, '%') + '%'

What is the best way to return results similar to the input?

In my database I am selecting from a field containing Dillon Brookfield. I tried searching for brookfield with the following statement thinking LIKE would select the data, but it didn't work.
SELECT *
FROM [Reports]
WHERE ([VisitorName] LIKE '%' + #VisitorName + '%'
OR [PlateNumber] = #PlateNumber)
I record people who have been banned from a property along with their plate (if known), but if their name is not put in exactly it doesn't return the value. What would be the best way to return similar results?
This is more like a comment, but there is code inside and the comment only allows one #.
What data type is your #PlateNumber? Is it CHAR or VARCHAR? it can make a difference. Like these tests.
DECLARE #char NCHAR(20) = 'space';
SELECT '%'+#char+ '%',IIF('space' Like '%'+#char+ '%', 1,0);
DECLARE #varchar NVARCHAR(20) = 'space';
SELECT '%'+#varchar+ '%',IIF('space' Like '%'+#varchar+ '%', 1,0);
The first SELECT will give you
'%space %',0. -- there will be 15 blank character between space and %
The second SELECT will give you
'%space%', 1.
Create fulltext index. Search names/addresses and other similar fields with fulltext search - it'll be faster and you can find all names - Dillon Brookfield vs Brookfield Dillon.

Quotes in variable

The variable #it_codigo is used to get a ntext value from other table in a procedure and is used for a select like:
SELECT * FROM anaProdutos WHERE cod_produto LIKE #it_codigo
But this doesn't work, missing quotes. I tried
''+#it_codigo+''
and
QUOTENAMES(#it_codigo, '')
But that didn't solve the problem.
If you're using LIKE you'd want something as per below;
LIKE '%' + #it_codigo + '%'
You need the percentage signs for the LIKE to work.
Try
WHERE cod_produto LIKE '%' + #it_codigo + '%'
Check this link for more information on LIKE keyword.

Is it possible to search for multiple terms in a column by using a LIKE statement?

I'm trying to understand if the above question is possible. I've been conceptually thinking about it, and basically what I'm looking to do is:
Specify keywords that may appear in a title. Lets use the two terms "Portfolio" and "Mike"
I'm hoping to generate a query that will allow for me to search for when Portfolio is contained within a title, or Mike. These two titles need not to be together.
For instance, if I have a title dubbed: "Portfolio A" and another title "Mike's favorite" I'd like both of these titles to be returned.
The issue I've encountered with using a LIKE statement is the following:
WHERE 1=1
and rpt_title LIKE ''%'+#report_title+'%'''
If I were to input: 'Portfolio,Mike' it would search for the occurrence of just that within a title.
EDIT: I should have been a bit more clear. I believe it's necessary for me to input my variable as 'Portfolio, Mike' in order for it to find the multiple values. Is this possible?
I'm assuming you could maybe use a charindex with a substring and a replace?
Yep, multiple Like statements with OR will work just fine -- just make sure you use the correct parentheses:
SELECT ...
FROM ...
WHERE 1=1
and (rpt_title LIKE '%Portfolio%'
or rpt_title LIKE '%Mike%')
However, I might suggest you look into using a full-text search.
http://msdn.microsoft.com/en-us/library/ms142571.aspx
I can propose a solution where you could specify any number of masks, without using multiple LIKE -
DECLARE #temp TABLE (st VARCHAR(100))
INSERT INTO #temp (st)
VALUES ('Portfolio photo'),('- Mike'),('blank'),('else'),('est')
DECLARE #delims VARCHAR(30)
SELECT #delims = '|Portfolio|Mike|' -- %Portfolio% OR %Mike% OR etc.
SELECT t.st
FROM #temp t
CROSS JOIN (
SELECT substr =
SUBSTRING(
#delims,
number + 1,
CHARINDEX('|', #delims, number + 1) - number - 1)
FROM [master].dbo.spt_values n
WHERE [type] = N'P'
AND number <= LEN(#delims) - 1
AND SUBSTRING(#delims, number, 1) = '|'
) s
WHERE t.st LIKE '%' + s.substr + '%'

T-SQL Split String Like Clause

I have declare #a varchar(100) = 'abc bcd cde def'. What I need is to select from a table where a column is like 'abc' or 'bcd' or 'cde' or 'def'. I can use a split function and a while to get what I want, but somewhere I saw a smart solution using replace or something similar and I just can't remember it.
I know I can use an xml variable, and parse it that way. However, the value is part of a large procedure, and the best way for me is to use it in string form.
I know I can solve this by building a dynamic sql query, but that is not an option in the domain I'm working in.
Damn, I just can remember the solution. Its a hack, a little dirty trick that do the job.
Anyways, I ll use the code bellow (Im over SQL Server 2008), is it a good idea? I prefer it over the dirty split. Is it more performatic?
declare #w varchar(100) = 'some word'
declare #f xml
set #f = '<word>' + replace(#w, ' ', '</word><word>') + '</word>'
select
template.item.value('.', 'varchar(100)') as word
from #f.nodes('/word') template(item)
Use a function to split the individual items into a table, one record per item. Then you simply join to that table.
insert into #FilterTable (filters)
select Items from dbo.Split(#YourFilterString)
select *
from YourTable yt
join #FilterTable f on f.filters = yt.YourColumn
Of course my example is using equality. It gets more complicated if you truly intend to use "like" with wildcards.
In tsql you can use a pattern col like '[abcd]'
http://msdn.microsoft.com/en-us/library/ms179859.aspx
For matching multiple words (not letter) and without dynamic SQL, you'll have to get the values into a temp table. For a split function try this page http://www.sommarskog.se/arrays-in-sql-2005.html#iterative and look at the List of Strings function iter_charlist_to_table.
Or maybe you are thinking of this little trick Parameterize an SQL IN clause from the SO CEO.
for 4 sections max
WHERE
PARSENAME(REPLACE(#a, ' ', '.'), 1) = 'xxx'
OR
PARSENAME(REPLACE(#a, ' ', '.'), 2) = 'xxx'
OR
PARSENAME(REPLACE(#a, ' ', '.'), 3) = 'xxx'
OR
PARSENAME(REPLACE(#a, ' ', '.'), 4) = 'xxx'