Logo of Microsoft SQL Server

SQL Server - Variables

Usage of simple variable with an example

Scenario

If you want to store a value of a column from a table, a variable will do the trick.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
-- You declare the variable with the prefix `@` and its type.
DECLARE @Total INT;

--Optionnally, you can set a default value
SET @Total = 0;
GO

-- You store the value you need into the variable
SELECT @Total = COUNT(*)
FROM dbo.Orders
WHERE OrderDate >= '2025-01-01';

Documentation

Reference: Microsoft Learn.

Follow me

Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.

Credits: Image from Microsoft Server

License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy