Assigning Results of Aggregate Functions
We can utilize this syntax to assign the result of an aggregate function, such as SUM(), AVG(), MAX(), or MIN(), to a variable for subsequent computations.
Example:
Suppose we want to calculate the total sales amount for a specific product and store it in a variable.
DECLARE @TotalSales MONEY;
SELECT @TotalSales = SUM(SalesOrderDetail.OrderQty * SalesOrderDetail.UnitPrice)
FROM Sales.SalesOrderDetail
JOIN Production.Product ON SalesOrderDetail.ProductID = Product.ProductID
WHERE Product.Name = 'Mountain-500 Black, 48';
Output:
Explanation: Here we have calculated little complex data based on join and stored it in the variable and we can use that variable to calculate further values.
SQL Server SELECT INTO @Variable
In the world of SQL Server, the SELECT INTO statement is a powerful syntax for retrieving data from one or more tables and inserting it into a new table. However, what if you want to store the result set of a SELECT query into a variable rather than a table? This is where the SELECT INTO @Variable syntax comes into play. In this article, weâll delve into the intricacies of using SELECT INTO @Variable in SQL Server, exploring its syntax, use cases, and best practices.
Contact Us