SQL Server › T-SQL Fundamentals & Syntax

How do you declare and use a variable in T-SQL?

Beginner

Answer

You declare a variable using the DECLARE keyword followed by its name, prefixed with an at sign, and its data type, then assign it a value using either SET or SELECT, after which you can reference that variable anywhere within the same batch or procedure to store and reuse values throughout your script.
DECLARE @CustomerName VARCHAR(100);
SET @CustomerName = 'John Smith';
SELECT * FROM Customers WHERE Name = @CustomerName;
Real-world example A script declares a variable to hold a customer's name, reusing that same variable across several subsequent queries instead of repeating the literal value throughout the script.

Common follow-ups: What is the difference between using SET and SELECT to assign a value to a variable?;What is the scope of a variable declared inside a stored procedure?