Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL concatenating strings?

Tags:

sql

sql-server

I have a query that takes input from the end user and compares it to 2 columns individually, and the two columns concatenated.

SELECT f_name, l_name, (f_name + ' ' + l_name) AS full_name
FROM users_table
WHERE f_name = user-input
   OR l_name = user-input
   OR 'full_name' = user-input

Excuse the massive syntax fail, but I assure you it's correct in the program.

It is written in PHP, querying a SQL SERVER 2005 database, and is case insensitive.

Typing one name (first or last) will return correct results, but typing first, then space, then last, returns an empty set.

Any ideas?


2 Answers

that is because 'full_name' is a literal and not a column name, it does not exists at the WHERE clause level

you need to add

OR f_name + ' ' + l_name = user-input

instead of OR 'full_name' = user-input

like image 93
SQLMenace Avatar answered Jun 21 '26 06:06

SQLMenace


Under the "teach a man to fish" theory ...

You cannot use a column alias in a where or group by clause. You can use it in an order by clause. To use a column alias the way you want to, you would have to do something like ...

SELECT [Full Name] FROM
  (SELECT f_name, l_name, f_name + ' ' + l_name AS [Full Name]
   FROM users_table)
  WHERE [Full_Name] = @paramVal
like image 30
JP Alioto Avatar answered Jun 21 '26 06:06

JP Alioto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!