Variables in SQL
1. DECLARE statement in SQL
In SQL, the DECLARE statement is used to define variables that can hold data values of a specific data type. Variables can be used to store values for later use within a batch of SQL commands or stored procedures.
SQL Syntax
DECLARE @variable_name datatype [ = initial_value ]
- @variable_name: This is the name of the variable, and it must begin with @.
- datatype: The data type of the variable (e.g., INT, VARCHAR, DATE, etc.).
- initial_value (optional): You can optionally assign an initial value to the variable when declaring it.
Examples: A) Declaring an integer variable:
SQL
DECLARE @count INT;
B) Declaring a date variable with an initial value:
SQL
DECLARE @startDate DATE = '2024-01-01';
C) Declaring a string (varchar) variable:
SQL
DECLARE @name VARCHAR(50) = 'Ashish';
2. Set statement in SQL
In SQL, a SET statement is used to assign a value to a variable.
a) Assigning a Value to a Variable
SQL
DECLARE @myVar INT;
SET @myVar = 10;
SET @myVar = 10;
b) Setting Multiple Variables
SQL
DECLARE @var1 INT, @var2 VARCHAR(50);
SET @var1 = 5;
SET @var2 = 'SQL Example';
SET @var1 = 5;
SET @var2 = 'SQL Example';