William
William

Reputation: 6610

How to assign a sum of values within fields to a variable?

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

Answers (3)

Erdinç Özdemir
Erdinç Özdemir

Reputation: 1381

First set @TotalAge:

set @TotalAge=(select sum(Age) from TableName)

then select @TotalAge where you want:

select @TotalAge

Upvotes: 15

Ambrose
Ambrose

Reputation: 511

use SET to assign some:

SET @TotalAge = (SELECT SUM(Age) FROM YourTable) 

Upvotes: 2

Mithrandir
Mithrandir

Reputation: 25377

You could use :

      SET @TotalAge = (SELECT SUM(Age) FROM YourTable) 

or

      SELECT @TotalAge  = SUM(Age) FROM YourTable

Upvotes: 3

Related Questions