Declare variables in SQL Server

SQL Server fully exists the concepts of data types, variables and declarations of variables as other programming languages. The article will learn how to declare a variable, multiple variables and assign default values ​​to variables in SQL Server.

SQL Server fully exists the concepts of data types, variables and declarations of variables as other programming languages. The article will learn how to declare a variable, multiple variables and assign default values ​​to variables in SQL Server. Invites you to read the track.

Variable (Variable) used to store temporary values ​​during the execution of the algorithm.

Syntax of variable declaration in SQL Server

To declare variables in SQL Server, we use the DECLARE statement, expressed as follows:

 DECLARE @variable_name datatype [ = initial_value ], 
@variable_name datatype [ = initial_value ],
.;

Parameters:

  1. variable_name : name assigned to the variable.
  2. datatype: data type of variable.
  3. initial_value: default value assigned to variable (optional).

Declare a variable in SQL Server

Use DECLARE to declare any variable

 DECLARE @quantrimang VARCHAR(50); 

This DECLARE statement declares a variable named @quantrimang, with VARCHAR data type and a length of 50 characters.

You then change the value of the @quantrimang variable using the SET statement.

 SET @quantrimang = 'Hello world'; 

Next try the INT data type:

 DECLARE @site_value INT; 

Use the SET statement to assign values ​​to the @site_value variable

 SET @site_value = 10; 

So the @site_value variable here is assigned to the integer 10.

Declare many variables in SQL Server

How to use the following command:

 DECLARE @quantrimang VARCHAR(50), 
@site_value INT;

In this example, we have two variables declared: @quantrimang variable with VARCHAR (50) data type and variable @site_value INT data type.

Declare the variable with the default value in SQL Server

In SQL Server, we can assign the default value to the variable at the time of declaration.

 DECLARE @quantrimang VARCHAR(50) = 'Hello world'; 

So here the @quantrimang variable with VARCHAR data type and the length of 50 characters are assigned by default to the 'Hello world' value.

Similarly, we declare with the INT data type:

 DECLARE @site_value INT = 10; 

Declare more than one variable with the initial value assigned

How to use the following command:

 DECLARE @quantrimang VARCHAR(50) = 'Hello world'; 
@site_value INT = 10;

The two variables @quantrimang and @site_value have been declared at the same command and assigned the default initial values.

Previous lesson: LITERAL (Hang) in SQL Server

Next post: SEQUENCE in SQL Server

4.5 ★ | 2 Vote | 👨 125 Views
« PREV POST
NEXT POST »