SQL Variable Declaration – How to Declare a Variable in SQL Server – SQL Training Online

Công Nghệ



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.
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.

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:
Google+:
LinkedIn:
Facebook:

Nguồn: https://bus-rush.info/

Xem thêm bài viết khác: https://bus-rush.info/cong-nghe/

17 thoughts on “SQL Variable Declaration – How to Declare a Variable in SQL Server – SQL Training Online

  1. Hi, greetings
    I wanna know how to pass a scalar variable in a like clause in the where condition.
    If anyone knows how, it will be helpfull.

    Best regards.

  2. Thank you. This tutorial was easy to understand. Now I can continue watching my CBT nuggets videos.. I didn't know what a DECLARE statement was with CBT, so I had to figure it out. You explained it perfectly.

Leave a Reply

Your email address will not be published. Required fields are marked *