In SQL, Variable is engaged to temporarily store and manipulate a value(s) that can be used within a block/set of SQL statement.
1. Variable Declaration
2. Variable Initialization/Assignment
3. Variable usage in statement
It is the first step in creating variable >> Specify variable name using the "@" prefix and it's data type, this process is known as 'variable declaration'. Variable is declared using the 'DECLARE' keyword.
Here's the syntax :
DECLARE @variable_name data_type;
Here's an example :
DECLARE @Employee_Id INT;
It is the second step in creating variable >> Assign a specific value to the declared variable, this process is known as 'variable Initialization' or 'variable assignment'. 'SET' keyword is used to assign a value to the declared variable.
Here's the syntax :
SET @variable_name = value;
Here's an example :
SET @Employee_Id = 5;
Reference the variable within the 'SELECT' statement to retrieve its value. 'SELECT' or 'PRINT' keyword is used to retrieve variable value.
Here's the syntax :
SELECT @variable_name; PRINT @variable_name;
Here's an example :
SELECT @Employee_Id; PRINT @Employee_Id;
SQL variables are placeholders used to store data temporarily within SQL scripts or stored procedures.
Variables are typically declared and assigned values within the SQL code.
In a database, a variable is a named storage location that holds a value, allowing for dynamic data manipulation.
An SQL table variable is a variable that holds a set of data like a table, often used in Transact-SQL scripts within SQL Server databases.