ou might expect all SQL Server's clauses to support a column alias. As reasonable as that assumption seems, SQL Server can't honor a column alias in that way. If you refer to an aliased column in another clause, SQL Server returns an errorsurprise! Figure 1 shows the result of running such a query; SQL Server can't find the aliased column TotalCost. That's not a bug; SQL Server requires the aliasit has to call the column something!
SQL Server returns the error in Figure 1 because its engine works logically through the calls as follows:
![]() Figure 1. SQL Server Engine Can't Find TotalCost: This error occurs because SQL Server can't find the aliased column. |
![]() Figure 2. The WHERE Clause Supports a Column Alias: ORDER BY is the only place SQL Server supports a column alias. |
The same thing will happen with a GROUP BY or HAVING clause that refers to a column alias. SQL Server can't apply an alias that it hasn't defined yet. Outside of SELECT's column list, ORDER BY is the only place SQL Server supports a column alias (see Figure 2).
![]() | |
| Figure 3. Use a Derived Table to Use a Column Alias: SQL Server successfully handles the column alias by virtue of the derived table. |
Yes, you have to rethink your strategy a bit to get the results you want, but it's a small price to pay for the convenience!
The derived table dtTotalCost retrieves all the columns the query needs, including the aliased (or derived) column. The main SELECT then handles the logistics of manipulating the dataany filtering, grouping, sorting, and so on. In this way, the column alias exists in memory (in the derived table) when the main SELECT's WHERE clause gets around to referring to it.
The rule is simple, even if it doesn't appear so by glancing at the SQL:
| DevX is a division of Internet.com. © Copyright 2010 Internet.com. All Rights Reserved. Legal Notices |