1

I want to make search by name and surname , and I use this Query(SUR - surname , NAM - name

Declare @name varchar(30) = 'Joh'  //part or full name/surname or both
SELECT (RTRIM(SUR) + ' ' + RTRIM(NAM)) AS name , W , SS FROM Table
WHERE name like '%' + @name + '%'

But I have an error

Invalid column name "name".

I need to make search by 2 columns in same time . This

(SUR like '%' + @name + '%') or (NAM like '%' + @name + '%') 

gave me search only by 1 column like : Search : Jones and I see Johnes but if i want search John Jones i will haven't result .

Help me to make search by 2 columns in same time.

2
  • 3
    You can't reference an alias like that - you'll need to either use a sub-select or replace your WHERE name LIKE with WHERE (RTRIM(SUR) + ' ' + RTRIM(NAM)) LIKE Commented Jun 26, 2015 at 13:56
  • @Siyual yea. thanks . It's so simple and good solution , that i did't think about it Commented Jun 26, 2015 at 13:59

2 Answers 2

4

you are not alowed to use alias name in where clause. you have to use your expression as it is in where clause

Declare @name varchar(30) = 'Surname'  
SELECT (RTRIM(SUR) + ' ' + RTRIM(NAM)) AS name , W , SS FROM Table
WHERE (RTRIM(SUR) + ' ' + RTRIM(NAM)) like '%' + @name + '%'
Sign up to request clarification or add additional context in comments.

Comments

0

You can use APPLY VALUES to achieve this as well.

It's not the best SQL design to begin with, as you won't be able to take advantage of indexing.

Declare @name varchar(30) = 'Joh';  //part or full name/surname or both

SELECT 
  Fullname.name AS name , 
  W , 
  SS 
FROM Table
OUTER APPLY(VALUES(RTRIM(SUR) + ' ' + RTRIM(NAM)) Fullname(name)
WHERE Fullname.name like '%' + @name + '%';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.