0

Is it possible to access a temporary column that was defined in a query for a Common Table Expression? Say I have

select * from myTable 

;with cte  as 
(
    select
        *, Salary * 4 as FourTimesSalary
    from 
        Employees
    where 
        Name = @name
        and ID >= 100 
)

Is there a way to use the temporary column FourTimesSalary when querying cte like so?

select top 2 *  
from cte  
order by FourTimesSalary, Name

TIA.

1 Answer 1

1

Yes you can do that. Example:

with temp as
(
    select 1 as id, 2*4 as val
    UNION
    select 2 as id, 3*4 as val
)
SELECT * FROM temp ORDER BY VAL desc

Your example looks fine, did you get an error when you tried that or something?

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, the error indicated I did not have column name FourTimesSalary defined. It turned out to be a problem within my query statement.

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.