Working wth Variables in Database Interactions with Transact-SQL - Using T-SQL variables efficiently: continued
(Page 4 of 4 )
We all know that finding the sum of values is very easy using the aggregate SUM as follows:
SELECT sum(UnitPrice * Quantity)
FROM [Order Details]
We can retrieve the sum in to a variable in a script as follows:
use Northwind
go
declare @sum numeric(10,2)
SELECT @sum = sum(UnitPrice * Quantity)
FROM [Order Details]
print @sum
go
The same can be achieved by further simplifying it as follows:
use Northwind
go
declare @sum numeric(10,2)
SET @sum = (SELECT sum(UnitPrice * Quantity)
FROM [Order Details])
print @sum
go
We can also use the recursive method as follows:
use Northwind
go
declare @RunningSum numeric(10,2)
set @RunningSum = 0.0
SELECT @RunningSum = @RunningSum + sum(UnitPrice * Quantity)
FROM [Order Details] as a
print @RunningSum
go
In the next article, I shall concentrate a bit more on variables, conditions, loops, DML statements and so forth. So please check back frequently or sign up for a newsletter! Any bugs, errors, improvements etc., are highly appreciated at http://jagchat.spaces.live.com.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |