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 ]

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;

b) Setting Multiple Variables

SQL

DECLARE @var1 INT, @var2 VARCHAR(50);
SET @var1 = 5;
SET @var2 = 'SQL Example';