Damozz
asked on
SQL - Updating Variable Values
Please can someone advise if it is possible to update a variable after the initial SET statement. I want the variable to be updated with a single value based on several other values added together.
SET @TotalDuration = (SELECT Averages.Repair + Averages.Invoiced FROM Averages)
Receiving "Incorrect syntax near SET..."
The variable will then be used in a subsequent query as opposed to repeating the calculation over and over.
SET @TotalDuration = (SELECT Averages.Repair + Averages.Invoiced FROM Averages)
Receiving "Incorrect syntax near SET..."
The variable will then be used in a subsequent query as opposed to repeating the calculation over and over.
ASKER
The averages table is a CTE... so I'm trying to set the variable immediately after
DECLARE @TotalDuration INT;
WITH
AVERAGES (Repair, Invoiced) AS
(
SELECT .....
)
SET @TotalDuration = (SELECT Averages.Repair + Averages.Invoiced FROM Averages)
The query works until I add the SET variable line which I intend to use for other calculations....
DECLARE @TotalDuration INT;
WITH
AVERAGES (Repair, Invoiced) AS
(
SELECT .....
)
SET @TotalDuration = (SELECT Averages.Repair + Averages.Invoiced FROM Averages)
The query works until I add the SET variable line which I intend to use for other calculations....
then it needs to be a SELECT and not a SET:
DECLARE @TotalDuration INT;
WITH
AVERAGES (Repair, Invoiced) AS
(
SELECT .....
)
SELECT @TotalDuration = Averages.Repair + Averages.Invoiced FROM Averages)
ASKER
Thanks that worked, can you clarify?
ASKER
Does this prevent me from referencing the Averages CTE after this statement
e.g.
SELECT Averages.Repair/@TotalDura tion
Also should the closing bracket on the above solution (line 8) be removed or is there an opening bracket missing?
Thanks
e.g.
SELECT Averages.Repair/@TotalDura
Also should the closing bracket on the above solution (line 8) be removed or is there an opening bracket missing?
Thanks
ASKER
Sorry the message I now receive is
Msg 208, Level 16, State 1, Line 158
Invalid object name 'Averages'.
Msg 208, Level 16, State 1, Line 158
Invalid object name 'Averages'.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
please clarify where/how you are using this?
did you dod the DECLARE variable?
please provide more of the code ...