SQL Server > Variables

Declaration & Usage of variable in SQL Server

How to declare and use a variable in SQL Server?


Variables can be declared in SQL Server using DECLARE keyword and the variable name in SQL Server is prefixed with “@” character.

A variable declaration starts with DECLARE keyword followed by @variableName and then the data type of the variable.

DECLARE @firstName varchar(50)

In above case, @firstName is the variable name that is of varchar type and its size is 50 (max characters can be stored in this variable is 50).

To set a value into the variable, we can use SET keyword followed by the variable name and then the value.

SET @firstName = 'Sheo'

To print the value stored into the variable, we can use PRINT keyword. The complete code snippet looks like below.

DECLARE @firstName varchar(50)
SET @firstName = 'Sheo'
PRINT @firstName

Running above set statements, ‘Sheo’ is written in the Message window.

 Views: 10300 | Post Order: 40



Write for us






Hosting Recommendations