3

What do I have to do to use name Rowss in the WHERE clause ?

SELECT TOP 10 
    ROW_NUMBER() OVER(ORDER BY dp.IdPytanie) AS Rowss,
    dp.IdPytanie
    ,dp.SpecjalnePytanie
 FROM dodajtemat_pytanie dp
 WHERE 
    (@RowBegining = 0 OR convert(int,Rowss) >= @RowBegining)
    AND (@RowEnd = 0 OR Rowss <= @RowEnd)

Error enter image description here

This work ->

 @RowEnd = 0 OR ROW_NUMBER() OVER(ORDER BY dp.IdPytanie) <= @RowEnd
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rafał Developer
  • 2,135
  • 9
  • 40
  • 72
  • 2
    You cannot reference in a WHERE clause an alias given to a column of the same query, you need to go with a subquery, or replace Rowss with its full expression. – A Hocevar Mar 13 '13 at 12:49
  • 4
    As you are on 2012 you might want to look at [`OFFSET ... FETCH`](http://stackoverflow.com/a/5620802/73226) – Martin Smith Mar 13 '13 at 13:42

1 Answers1

7

Use a subquery or a CTE like this:

WITH CTE
AS
(
    SELECT 
      ROW_NUMBER() OVER(ORDER BY dp.IdPytanie) AS Rowss,
      dp.IdPytanie,
      dp.SpecjalnePytanie
    FROM dodajtemat_pytanie dp
)
SELECT *
FROM CTE
WHERE (@RowBegining = 0 OR Rowss >= @RowBegining)
  AND (@RowEnd      = 0 OR Rowss <= @RowEnd);

The WHERE clause is logically evaluated before the SELECT statement, so that it doesn't recognize that newly created alias Rowss.

Fore more information about the logical query processing steps in SQL Server, see:

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164