Question : Multiply Values within a Stored Procedure

I am running a stored procedure and I want to calcualte a value and then use it again in subsequent calculations.

Here is a stripped down version of the code that I am using which demonstrates my question.

I know there is an easy way, by putting it all in one calculation to give TotalA4Cost, but this results in lines and lines of code when used in the full version which has many calculations using TotalA4Cost.

I would therefore like to be able to reference TotalA4Cost without having to state its calculation everytime.

When I execute this code I get the error that "TotalA4Cost is an invalid Column Name".
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
ALTER PROCEDURE [dbo].[SectionCost] 
(
	@SectionID int
)
 
AS
	
SELECT
	
	
	S.SectionID, 
	S.SectionName, 
	S.OriginalCountBW * P.A4BW AS BWA4Cost, 
	S.OriginalCountColor * P.A4Colour AS ColA4Cost, 
	
                     BWA4Cost + ColA4Cost AS TotalA4Cost,
 
                     TotalA4Cost * 0.5 AS HalfA4Cost
 
 
	FROM
	tblSections S
		INNER JOIN tblSectionPaperColor SPC ON SPC.SectionPaperColorID = S.SectionPaperColorID
		LEFT OUTER JOIN tblPrice P ON P.PriceID = S.PriceID
 
	
	WHERE S.SectionID= @SectionID
Open in New Window Select All

Answer : Multiply Values within a Stored Procedure

OK, here's a derived table solution:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
ALTER PROCEDURE [dbo].[SectionCost] 
(
        @SectionID int
)
 
AS
 
Select SectionID, SectionName, BWA4Cost, ColA4Cost, TotalA4Cost,
 
                     TotalA4Cost * 0.5 AS HalfA4Cost,
-- More calculations w/ TotalA4Cost ...
From        
(SELECT
        
        
        S.SectionID, 
        S.SectionName, 
        S.OriginalCountBW * P.A4BW AS BWA4Cost, 
        S.OriginalCountColor * P.A4Colour AS ColA4Cost, 
        
                     BWA4Cost + ColA4Cost AS TotalA4Cost
 
 
        FROM
        tblSections S
                INNER JOIN tblSectionPaperColor SPC ON SPC.SectionPaperColorID = S.SectionPaperColorID
                LEFT OUTER JOIN tblPrice P ON P.PriceID = S.PriceID
 
        
        WHERE S.SectionID= @SectionID) DT
Open in New Window Select All
Random Solutions  
 
programming4us programming4us