DECLARE @variable (TSQL Statement)

declares a new variable.

Syntax

DECLARE { @variable [AS] datatype [= initial_value] } [,...n] 

Arguments

@variable
is the name of the new variable. Must start with @.
datatype
is a valid datatype.
  • The default precision for varbinary, varchar and char is 1 if not specified.
  • The default precision for numeric is 18 if not specified.
initial_value
is the initial value to be assigned to @variable.

Remarks

Variable names must start with the character @.

If there is no initial_value, the variable is initialized with a NULL value.

To assign values to a variable, use SET @variable.

Examples

CREATE TABLE t (a INT NOT NULL IDENTITY PRIMARY KEY, b VARCHAR(20));
GO

DECLARE @s      VARCHAR(40) = 'bakoluenopukybnoachoxutipomunega';
DECLARE @i      INT = 0;
DECLARE @j      INT;
DECLARE @name   VARCHAR(30);
DECLARE @start  INT;
DECLARE @length INT;

WHILE @i < 4
    BEGIN

    SET @name = '';
    SET @j    = 0;
    WHILE @j < 5
        BEGIN
        SET @start  = RAND()*LEN(@s);
        SET @length = RAND()*4 + 1;
        SET @name  += SUBSTRING(@s, @start, @length); -- add a random fragment of @s

        SET @j += 1;
        END

    INSERT INTO t(b) VALUES (@name); -- @name is a random string

    SET @i += 1;
    END

SELECT * FROM t;

The result is:

a          |b                   |
-----------+--------------------+
          1|molunegbakeno       |
          2|xnkybnenopmu        |
          3|babakipoomuho       |
          4|koybnonoapop        |

(4 row(s) affected)
RSQL, a simple alternative to Microsoft SQL Server