Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : summing two variables

Tags:

sql

sql-server

I am trying to add two variables

DECLARE @RentsSum MONEY
SET @RentsSum = (SELECT SUM(Price)
                 FROM Rents
                 WHERE StartDate IS NOT NULL)
GO

DECLARE @SalesSum MONEY
SET @PriceSum = (SELECT SUM(Price)
                 FROM Purchases
                 WHERE DateBought IS NOT NULL)
GO

DECLARE @SalesAndRentsSum MONEY

SET @SalesAndRentsSum = @RentsSum + @PriceSum;

SELECT @SalesAndRentsSum

into one but I get some strange errors here...

Must declare the scalar variable "@PriceSum".

Must declare the scalar variable "@RentsSum".

like image 647
MitkoZ Avatar asked Mar 02 '26 10:03

MitkoZ


2 Answers

Remove all the GO words. You have three separate batches here and the variable must be declared within the scope of that batch.

DECLARE @RentsSum MONEY, @SalesSum MONEY, @SalesAndRentsSum MONEY

SET @RentsSum = (SELECT SUM(Price)
                FROM Rents
                WHERE StartDate IS NOT NULL)

SET @SalesSum = (SELECT SUM(Price)
                FROM Purchases
                WHERE DateBought IS NOT NULL)

SET @SalesAndRentsSum = @SalesSum + @PriceSum

SELECT @SalesAndRentsSum
like image 115
S3S Avatar answered Mar 04 '26 22:03

S3S


DECLARE @RentsSum MONEY
DECLARE @PriceSum MONEY
DECLARE @SalesAndRentsSum MONEY

SET @RentsSum = (SELECT SUM(Price)
                FROM Rents
                WHERE StartDate IS NOT NULL)


SET @PriceSum = (SELECT SUM(Price)
                FROM Purchases
                WHERE DateBought IS NOT NULL)


SET @SalesAndRentsSum=@RentsSum+@PriceSum;
SELECT @SalesAndRentsSum
like image 40
LONG Avatar answered Mar 04 '26 23:03

LONG