Friday, March 9, 2012

Reference an alias field name in an SQL Statement

Is there a way to Reference an alias field name in an SQL Statement?
Example:
Select
1 + 1 AS F1,
F1 + 1 AS F2Hello Kent,
Darren has given a good answer to your problem. I use derived tables or
sub queries to handle the kind of functionality you are looking for.
Your example shows two columns one contains a table field with a
calculation. The second has another calculation based on the first
field. Using derived tables is a very effect way to handle complex set
operations and calculations. Check out the script below.
CREATE TABLE [MyTable] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[F1] [int] NULL
) ON [PRIMARY]
GO
INSERT INTO [sandpit].[dbo].[MyTable]( [F1])
VALUES( 100)
GO
SELECT T.F1, T.F1+1 AS F2 FROM (SELECT ID, F1+1 AS F1 FROM MyTable) AS
T
GO
DROP TABLE MyTable
GO
I hope this makes it a bit clearer. I might help if you give the group
a bit more background on what you are trying to do.
Myles Matheson
Data Warehouse Architect
http://bi-on-sql-server.blogspot.com/
Kent Prokopy wrote:
> Is there a way to Reference an alias field name in an SQL Statement?
> Example:
> Select
> 1 + 1 AS F1,
> F1 + 1 AS F2|||Hello Kent,
Darren has given a good answer to your problem. I use derived tables or
sub queries to handle the kind of functionality you are looking for.
Your example shows two columns one contains a table field with a
calculation. The second has another calculation based on the first
field. Using derived tables is a very effect way to handle complex set
operations and calculations. Check out the script below.
CREATE TABLE [MyTable] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[F1] [int] NULL
) ON [PRIMARY]
GO
INSERT INTO [sandpit].[dbo].[MyTable]( [F1])
VALUES( 100)
GO
SELECT T.F1, T.F1+1 AS F2 FROM (SELECT ID, F1+1 AS F1 FROM MyTable) AS
T
GO
DROP TABLE MyTable
GO
I hope this makes it a bit clearer. I might help if you give the group
a bit more background on what you are trying to do.
Myles Matheson
Data Warehouse Architect
http://bi-on-sql-server.blogspot.com/
Kent Prokopy wrote:
> Is there a way to Reference an alias field name in an SQL Statement?
> Example:
> Select
> 1 + 1 AS F1,
> F1 + 1 AS F2

No comments:

Post a Comment