SELECT a.imageID, a.categoryID
FROM (SELECT * FROM
(SELECT *, ROW_NUMBER() OVER(ORDER BY PaymentID) AS RowNo FROM WP_advConfirmed) AS c WHERE c.ROWNo=2) AS a
INNER JOIN WP_advCategory AS b
ON a.categoryID = b.categoryID
WHERE a.categoryID = @categoryID
Try this query. Actually the problem is in this line "sql.AppendLine("WHERE RowNo = 2");"
You are trying to get the value of "RowNo" in the same select statement's where clause, where it is being generated .The value is not available at the given point.