DECLARE statement

Description

Declares a SQL variable within a compound statement (BEGIN... END).

Syntax

DECLARE variable_name data-type

Examples

Example 1

This batch illustrates the use of the DECLARE statement and prints a message on the server window:

BEGIN
  DECLARE varname CHAR(61);
  SET varname = 'Test name';
  MESSAGE varname;
END

Usage

Variables used in the body of a procedure can be declared using the DECLARE statement. The variable persists for the duration of the compound statement in which it is declared and must be unique within the compound statement.

The body of a procedure is a compound statement, and variables must be declared immediately following BEGIN. In a Transact-SQL procedure or trigger, there is no such restriction.

Standards

Permissions

None