T-SQL Tutorial

SQL Declare variable string


Declare variable string

To declare a string variable, use the DECLARE keyword, then type the @variable_name and variable type: char, varchar.
To assign a value to a variable, use the keyword SET.
The CHAR is a data type with fixed length and loads empty spaces. To remove the empty spaces uses functions LTRIM(remove leading spaces) and RTRIM(remove trailing spaces).
The VARCHAR is a data type with variable length and uses only the length loaded with characters.

Example

USE model;
GO
DECLARE @char AS char(10);
DECLARE @varchar AS varchar(10);
SET @char = 'test 1';
SET @varchar = 'test 2';
PRINT LTRIM(RTRIM(@char)) + ', ' + @varchar;
GO

Result:

test 1, test 2





Declare variable varchar

USE model;
GO
DECLARE @myString AS varchar(4000);
SET @myString = 'select name, description from Certifications where id in (2,3)';
EXECUTE(@myString);
GO

Result:

namedescription
SQL certificationBasic of SQL
T-SQL certificationBasic of T-SQL