Retrieving Scalar Values
If your query returns a single value, such as the result of a calculation or a configuration setting, SELECT INTO @Variable can capture and store it efficiently.
Example:
Assume we want to retrieve the standard cost of a specific product and store it in a variable.
DECLARE @StandardCost MONEY;
SELECT @StandardCost = StandardCost
FROM Production.Product
WHERE Name = 'Mountain-500 Black, 48';
SELECT @StandardCost AS StandardCost
Output:
Explanation: Here we’re retrieving a single value directly from a specific column in a table and storing it in a variable. This is useful when you need to capture a specific piece of data, like a configuration setting, a constant value, or any scalar value stored in the database.
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