T-SQL Tutorial

T-SQL Variables - Declare and Set variable


1. What is a Variable?

A Transact-SQL local variable is an database object that can store a single data value of a specific type.

2. Declare a Transact-SQL Variable

To declare a variable uses the keyword DECLARE, assign a variable name and a data type.

DECLARE @MyVariable datatype;

3. Set a Variable Value

After a variable is declared, it gets the default NULL value. To assign a value to a variable, use the SET statement.

4. Example

USE model;
GO
DECLARE @count int;
DECLARE @name varchar(250);
DECLARE @dsp varchar(250);
SET @count=0;
SET @dsp='Basic of T-SQL';
select @count = count(*) from Certifications;
IF @count > 0
    BEGIN
       select @name=name
       from Certifications
       where description=@dsp;
       PRINT @name
    END;
ELSE
    BEGIN
       PRINT 'Empty table'
    END;
GO

Result:

T-SQL certification