3
select 
   sp_una_stl_key, 
   row_number() over(order by sp_una_stl_key)as stl_key 
from        
    t_unit_data_archive
where 
    stl_key>=10

This query is not executed, throws,

Msg 207, Level 16, State 1, Line 2 Invalid column name 'stl_key'.

i could not understand what is the problem. please help me!

0

3 Answers 3

8

You can't use the ROW_NUMBER directly - you need to package it inside a Common Table Expression like this:

with CTE as
(
  select 
     sp_una_stl_key, row_number() over(order by sp_una_stl_key) as stl_key 
  from 
     t_unit_data_archive
)
select *
from CTE
where stl_key >= 10

Marc

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

5 Comments

I'm pretty sure you don't "have to" package it in a cte. You can use it in a regular select statement.
that is right you don't need to use a CTE, you can do a subquery or repeat the row_number in the WHERE clause
@SQLMenace2: yes, a subquery would work too, I find CTE clearer, though
@SQLMenace: It can not be repeated in the where clause, at least not on SQL Server 2005. (Did that change in 2008?)
You're right, I didn't consider this in my answer (which I deleted now). I just checked it - it doesn't work in SQL Server 2008 as well.
1

another way although I would prefer CTE

select * from (select 
   sp_una_stl_key, 
   row_number() 
   over(order by sp_una_stl_key)as stl_key 
from        
    t_unit_data_archive) x
where 
    stl_key>=10

Comments

1

you can't use the aliased field in the where clause. This should work:

select * from 
(select sp_una_stl_key, row_number() over(order by sp_una_stl_key)as stl_key 
from t_unit_data_archive) a
where stl_key>=10

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.