3

I am writing a sql server query with one column as a expression like

Select name , name + age as Test from myTable
where Test like '%b%';

Now i cannot use Test either i need to write

Select name , name + age as Test from myTable
where (name + age) like '%b%';

Now the expression (name + age) can be very big sometimes so cant i give it some alias and use it

Any help is appreciated,

Thank You

3
  • May I know what is reason you want to do that way? You want to find any record that match your filter criteria in either name or age column? Commented Feb 3, 2012 at 6:55
  • @ThitLwinOo because sometimes my expression is too big so i want to use some alist, so i put the question here so that i may know whether this is possible or not Commented Feb 3, 2012 at 6:58
  • Ok, I provided one answer, please try. Let me know it is ok for what you want. Commented Feb 3, 2012 at 7:01

2 Answers 2

6

How about this way..

select name, Test
(
Select name , (name + age) as Test from myTable
) t
where Test like '%b%'

The query needs to be modified as it has syntax error:

So it should be written like

select name from
(
Select name , (name + age) as Test from myTable
) t
where Test like '%b%'
Sign up to request clarification or add additional context in comments.

Comments

2

You can use cross apply like this

select M.name , T.Test
from myTable as M
  cross apply(select name + age) as T(Test)
where T.Test like '%b%';

5 Comments

+1 for Cross Apply. But it is little costlier affair if compared to Thit' answer.
@AmarPalsapure - The tests I have made does not show any difference in query plans or execution times.
In the execution plan, Compute Scalar step is added, it addes to CPU cost. It's not very significant though, may be because my DB size is small.
@AmarPalsapure - There is a Compute Scalar step in the derived table query as well. (SQL Server 2008)
Cross checked, the query from Thit was giving different output. Now checked everything, looks same. No difference at all. My bad. Apologies.

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.