Solved

refer to new field in query

Posted on 2004-10-13
4
418 Views
Last Modified: 2008-01-09
How do I refer to a newly created field in a query
for example

SELECT X+1 AS Y, Y+1 AS Z
FROM myTable

In the above I get an error when I try to refer to Y - this would work OK in MS Access
0
Comment
Question by:cdhbs
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 15

Accepted Solution

by:
jdlambert1 earned 65 total points
ID: 12303573
You can't refer to a column alias in the same SELECT statement. You can use a subquery or better, just repeat the formula (or it's logic combined with the additional logic):

SELECT X+1 AS Y, X+2 AS Z
FROM myTable
0
 
LVL 69

Assisted Solution

by:Scott Pletcher
Scott Pletcher earned 60 total points
ID: 12303593
If it's a complex expression, the subquery method might be easier:


SELECT y, y+2 AS z
FROM (
    SELECT x+1 AS y
    FROM myTable
) AS derived


Note that you must provide an alias for the derived query ("AS derived") and be sure not to use the original table name (such as "AS myTable") -- that can "confuse" SQL Server a lot, so just don't do it.
0
 
LVL 5

Expert Comment

by:waelothman
ID: 12304036
why not
SELECT X+1 AS Y, X+2 AS Z
FROM myTable

0
 

Author Comment

by:cdhbs
ID: 12304078
Thanks, the subquery is obviously the way to go in my case - Y in this case is actually 700 lines of code.
0

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question