411 REFERENCE · Wikibooks
Microsoft SQL Server/Variables
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
Declaration and affectation
Every variable name begins with an at.
Integer operations:
declare @i int
set @i = 5
declare @j int
set @j = 6
print @i+@j -- displays 11
Character operations:
declare @k char
set @k = '5'
declare @l char
set @l = '6'
print @k+@l -- displays 56
Types
The possible variable types are similar to the table fields oneshttps://msdn.microsoft.com/en-US/library/ms187752.aspx:
Characters
Those beginning by "n" are in Unicode format.
char, nchar, nvarchar, ntext, text, varchar.
To save a few memory space, it's possible to set a characters number limit during the declaration:
varchar(255)
The variable of characters maximum size is 2 GBhttps://msdn.microsoft.com/en-US/library/ms176089.aspx :
varchar(MAX)
Numbers
decimal, int (tinyint, smallint, bigint), float, money, numeric, real, smallmoney.
Dates
date, datetime, datetime2, datetimeoffset, smalldatetime, time.
Personalized types
In addition to the native types, it's possible to create one's own data types with CREATE TYPE.
Type determination
The function SQL_VARIANT_PROPERTY returns a given field typehttps://msdn.microsoft.com/en-us/library/ms178550.aspx. Example:
SELECT SQL_VARIANT_PROPERTY(Field1, 'BaseType')
FROM table1
References