简体   繁体   中英

SQL Server Paging query using a column alias

I am trying to create a query that I can then use for a paging system here is the query as it stands

SELECT   
   SLCustomerAccountID, 
   CustomerAccountNumber, 
   CustomerAccountName, 
   (MainTelephoneAreaCode +  MainTelephoneSubscriberNumber) AS PhoneNumber,
   Row_Number() over (order by CustomerAccountName) as RowIndex 
FROM         
   SLCustomerAccount
WHERE   
   CustomerAccountName LIKE '%green%' 
   AND RowIndex BETWEEN 10 AND 30
ORDER BY 
   CustomerAccountName

This query errors with

Invalid column name 'RowIndex'.

because I am trying to use the alias, but I am not sure of the correct way to set this so I can use the data that is in the column RowIndex

Here is what the query returns without the where clause

   ID1      ID2      NAME    Number  Row number
__________________________________________
| 12374927| 00010014|Some name| ******| 1|
| 51744   | 6631    |Same name| ******| 2|

You cannot use an alias in the WHERE (only in the ORDER BY ). But you can access it from a CTE:

WITH CTE AS
(

    SELECT SLCustomerAccountID, 
           CustomerAccountNumber, 
           CustomerAccountName, 
           (MainTelephoneAreaCode +  MainTelephoneSubscriberNumber) AS PhoneNumber,
           Row_Number() over (order by CustomerAccountName) as RowIndex 
    FROM   SLCustomerAccount
    Where CustomerAccountName LIKE '%green%' 
)
SELECT SLCustomerAccountID, 
        CustomerAccountNumber, 
        CustomerAccountName, 
        (MainTelephoneAreaCode +  MainTelephoneSubscriberNumber) AS PhoneNumber
FROM CTE
WHERE RowIndex Between 10 AND 30
ORDER BY CustomerAccountName

Query executes in following order in SQLSERVER-

1. FROM
2. ON
3. JOIN
4. WHERE
5. GROUP BY
6. WITH CUBE or WITH ROLLUP
7. HAVING
8. SELECT
9. DISTINCT
10. ORDER BY
11. TOP

so here in this case WHERE clause will be executed before the SELECT clause. So the alias column name will not be available in WHERE clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM