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.
- SQL Server Variables start with ‘@’.
- You must use the DECLARE keyword.
- You can use SET or SELECT to put data into the variable.
So, know I want to show you an example.
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.
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.
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 @[email protected]_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 @[email protected]_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: https://www.sqltrainingonline.com
Leave a Question, Comment, or Reply. All are welcome!