Reputation: 6610
I have an SQL statement which selects various data from a table in my database and I have declared variables within my code like:
DECLARE @TotalAge int;
Let's say one of the fields in the table is Age
, how would I sum the collected values from the query and assign them to the variable as a total?
Upvotes: 5
Views: 35634
Reputation: 1381
First set @TotalAge
:
set @TotalAge=(select sum(Age) from TableName)
then select @TotalAge
where you want:
select @TotalAge
Upvotes: 15
Reputation: 511
use SET
to assign some:
SET @TotalAge = (SELECT SUM(Age) FROM YourTable)
Upvotes: 2
Reputation: 25377
You could use :
SET @TotalAge = (SELECT SUM(Age) FROM YourTable)
or
SELECT @TotalAge = SUM(Age) FROM YourTable
Upvotes: 3