Variables can be used to store the
data in temporally based on data type.
Variable name begin with @ symbol.
There are two types of variables in
T-SQL.
1. Local Variables (It must begin
@ symbol).
2. Global Variables (it must begin
@@ symbol) this variables also known as system variables.
Syntax Declare a Variable
DECLARE @Variable-Name DATATYPE
EXAMPLE:
DECLARE @Name VARCHAR(100)
In before 2008 versions of SQL
SERVER we declare a variable and assign a value in 2 lines.
DECLARE @Name VARCHAR(100)
SET @Name='LeadFirstSQL'
In 2008 and Later versions of SQL
SERVER we declare a variable and assign a value in single line.
DECLARE @Name VARCHAR(100) ='LeadFirstSQL'
Variables must be declare and used
with the same batch.
DECLARE @Name VARCHAR(100) ='LeadFirstSQL'
SELECT @Name AS Nam
GO
SELECT @Name AS Name
If we are trying to execute above
statement we get the error. Because of before the GO all the Queries are
treated as single batch after the GO it treated as different batch.
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable
"@Name".
Comments
Post a Comment