Back to Blog

tsql

SQL Variable Declaration - How to Declare a Variable in SQL Server

Declare and use variables in T-SQL scripts. Learn DECLARE, SET, and SELECT statements for variable assignment in SQL Server.

3 min read

Last updated on

Video: SQL Variable Declaration - How to Declare a Variable in SQL Server - SQL Training Online

In this video, I show you how to Declare a Variable in SQL Server using SQL Server Management Studio.

How do you declare a variable in SQL Server?

There are 3 things to know when [declaring a SQL Server variable.aspx).

  1. SQL Server Variables start with -@-.

  2. You must use the DECLARE keyword.

  3. You can use SET or SELECT to put data into the variable.

So, know I want to show you an example.

SQL Variable Declaration

The first step is to create an empty variable. You do that with the DECLARE statement like this:

DECLARE @my_int int;

Here I have declared a variable that can store an integer.

The next step is to put something into the variable. You can do that by using the SET or the SELECT statements.

SET @my_int=3;

In that example, the variable will store the integer 3.

Then, the** last step is to print out what is in the variable**. You can do that with the SQL SELECT.

SELECT @my_int;

And that is it. But, you have to** run the whole thing together** for it to work.

DECLARE @my_int int;

SET @my_int=3;

SELECT @my_int;

Now, you can also change what is stored in the variable. In the following example, I change the value inside of the @my_int variable from 3 to 3+1 which equals 4.

DECLARE @my_int int;

SET @my_int=3;

SET @my_int=@my_int + 1;

SELECT @my_int;

And, the last thing I want to do is show you how to use the SELECT to populate the variable instead of the SET.

DECLARE @my_int int;

SELECT @my_int=3;

SET @my_int=@my_int + 1;

SELECT @my_int;

That-s it. That is how you do a SQL Variable Declaration.

Let me know what you think by commenting or sharing on twitter, facebook, google+, etc.

If you enjoy the video, please give it a like, comment, or subscribe to my channel.

You can visit me at any of the following:

SQL Training Online: /

Twitter: http://www.twitter.com/sql_by_joey

Google+:

LinkedIn: http://www.linkedin.com/in/joeyblue

Facebook: http://www.facebook.com/sqltrainingonline

About Joey Blue

Joey Blue teaches practical data skills that companies actually use. With 25+ years of experience solving real data problems for Fortune 500 companies, he's helped 152,000+ students learn SQL, Power BI, reporting, and modern analytics—cutting straight to what works.