Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate row values for use in WHERE clause of T-SQL query

I want to write a query in T-SQL to perform a search on two concatenated columns. The two columns are fname and lname. Here is what I have so far:

SELECT
    fname,
    lname,
    ...
FROM
    users
JOIN
    othertable ON foo=bar
WHERE
    fname+' '+lname LIKE '%query%'

SQL server doesn't like that syntax, though. How do I structure the query so that I can perform a WHERE LIKE operation that searches through two concatenated columns, allowing me to search the user's full name, rather than just first name and last name individually?

like image 580
Adam Avatar asked Sep 22 '10 20:09

Adam


People also ask

How do I concatenate row values in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

Can we use in operator with WHERE clause?

The SQL IN Operator The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.


2 Answers

I can only suggest that one of fname or lname is NULL so the LIKE fails., (NULL concat anything is null)

Try

...
ISNULL(fname, '') + ' ' + ISNULL(lname, '') LIKE '%query%'

However, I would use a computed column and consider indexing it because this will run awfully.

like image 194
gbn Avatar answered Nov 02 '22 10:11

gbn


My suggestion is to add a calculated column to your table for full_name calculated column examples:

--drop table #test
create table #test (test varchar (10) , test2 varchar (5),[Calc]  AS right(test, 3))
Insert #test
values('hello', 'Bye')
Insert #test
values('hello-bye', null)


Alter table #test
add [MyComputedColumn]  AS substring(test,charindex('-',test), len(test)),
Concatenatedcolum as test+ ' ' +test2
select * from #test

As you can see you may have to play around a bit until you get the results you want. Do that in a temp table first to avoid having to restructure the database table multiple times. For names, especially if you are using middle name which is often blank, you may need to add some code to handle nulls. You may also need to have code sometimes to cast to the same datatype if one filed you are concatenating is an int for instance and the other a varchar.

like image 26
HLGEM Avatar answered Nov 02 '22 11:11

HLGEM