DECLARE
DECLARE is a statement in SQL that is used to define a variable. This variable is then accessible only within the scope of the immediate script or procedure wherein it has been declared. The types of these variables can vary from integer, date, or even custom type.
Example
DECLARE @MyVar int;SET @MyVar = 5;SELECT @MyVar AS 'Value';
Output
| Value ||-------|| 5 |
Explanation
In the given example, a declaration of an integer variable @MyVar
is made, and it is set to 5
. The SELECT
statement is then used to display the value of @MyVar
.
# Example
```sqlDECLARE @animal VARCHAR(20);SET @animal = 'Lion';SELECT @animal as Animal;
Output
Animal |
---|
Lion |
Explanation
In the example code, a variable named ‘@animal’ is declared with the type of ‘VARCHAR(20)’. Then, the variable ‘@animal’ is set to hold the value as ‘Lion’. Finally, the data stored in ‘@animal’ is selected and returned, which will give us the output of ‘Lion’.
Example
DECLARE @FirstName nvarchar(50);SET @FirstName = 'John';SELECT @FirstName AS 'First Name';
Output
First Name----------John
Explanation
In the provided SQL Server example, the DECLARE
keyword is used to create a variable named @FirstName
of type nvarchar(50)
. The SET
keyword is then used to assign the value ‘John’ to the @FirstName
variable. Finally, the SELECT
statement is used to display the value of @FirstName
.
Example
DECLARE Value_1 NUMBER;BEGIN Value_1 := 10; DBMS_OUTPUT.PUT_LINE ('The value of Variable Number is ' || Value_1);END;
Output
The value of Variable Number is 10
Explanation
In the above SQL script, a variable ‘Value_1’ of type NUMBER is declared. Subsequently, a value of 10 is assigned to this variable. Finally, the value of the variable is output using the DBMS_OUTPUT.PUT_LINE command. This output is displayed under the shell.