tags:

views:

214

answers:

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!

+8  A: 

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

marc_s
I'm pretty sure you don't "have to" package it in a cte. You can use it in a regular select statement.
Joel Potter
Thank you very much
Sarathi1904
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
SQLMenace
@SQLMenace2: yes, a subquery would work too, I find CTE clearer, though
marc_s
@SQLMenace: It can not be repeated in the where clause, at least not on SQL Server 2005. (Did that change in 2008?)
Shannon Severance
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.
haarrrgh
+1  A: 

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
SQLMenace
+1  A: 

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
HLGEM