I have a SQL statement which is being used to page the results using ROW_NUMBER()
SELECT * FROM (
SELECT
ROW_NUMBER() OVER ( ORDER BY [tbl1].[Col1] ASC ) As RowNumber,
[tbl1].[Col1],
[tbl1].[Col2],
[tbl1].[Col3],
( SELECT [tbl2].[Col1]
FROM [tbl2]
WHERE [tbl2].[id] = [tbl1].[id]
AND [tbl2].[subid] = 2 ) As theColumnName
FROM
[tbl1]
) As tbl
WHERE RowNumber BETWEEN 1 AND 10
This all works fine and as expected. However I now want to introduce some additional ORDER BY functionality based on a value passed into the stored procedure.
So I have updated my ROW_NUMBER() OVER (ORDER BY... statement to
ROW_NUMBER() OVER (ORDER BY
CASE WHEN @sortBy = 'type1' THEN [tbl1].[Col1]
WHEN @sortBy = 'type2' THEN [tbl1].[Col2]
END,
CASE WHEN @sortBy = 'type3' THEN [tbl1].[Col3]
END
ASC) As RowNumber
As you can see here I have a CASE statement within the OVER () method, and there are two CASE‘s because [Col3] is a different data type than the other colums.
Now this works fine, but I cannot find out how to order by my column theColumnName as I just receive the error message Invalid column name 'theColumnName'.
WHEN @sortBy = 'type4' THEN theColumnName
I have even tried to use the column number, e.g. WHEN @sortBy = 'type4' THEN 5 but this will not work either.
Is there a way to Order By this custom column name?
You need to move the subquery to the
fromclause, such as:Now, you will be able to include
t2.col1in therow_number() order byclause.