VARCHAR (TSQL Datatype)

Is a variable-length string datatype, with precision being the maximum character length.

Syntax

VARCHAR [( precision )]

Range

The range of precision is 1 to 8000.

The storage size of a varchar data is not affected by the value of precision. Only the actual size of the data consumes memory or disk space.

Remarks

All varchar objects (variables, columns, literal strings) have a collation attribute. By default, it is the server default collation, unless overriden by a specific COLLATE clause.

The varchar datatype can hold any unicode character, as it is internally encoded as utf-8.

Literal Varchar String

A literal varchar string is a string enclosed by single quotes. It is of type varchar, not char.

If the string contains a single quote, it must be represented as two single quotes.

If the option QUOTED_IDENTIFIER is OFF, the string can also be enclosed by double quotes.

''                    -- empty string
'Hello World'
'Владивосток'
'O''Hara'
"O'Hara"              -- allowed if option QUOTED_IDENTIFIER is OFF

N'Hello'              -- MS SQL Server uses the prefix 'N' for unicode strings. RSQL ignores it.

e'H\u00e9l\u00e8ne'   -- RSQL syntax, allowing use of \uxxxx, \Uxxxxxxxx, \n, \r, \t

The prefix N is only used by MS SQL Server for unicode strings. RSQL just ignores it, as all strings are unicode.

The prefix e is only used by RSQL. The string can contain \uxxxx, \Uxxxxxxxx, \n, \r, \t escape sequences.
\uxxxx and \Uxxxxxxxx are unicode point, with x being hexadecimal digits.

It is possible to write a long string on multiple lines for readability, by putting a backslash \ at the end of the line:

PRINT 'This is a very \
long line';

Examples

DECLARE @a VARCHAR(100) = 'Hello';
DECLARE @b VARCHAR(100);
DECLARE @c VARCHAR;      -- default precision is 1

SET @b = 'O''Hara';
SET @c = 'x';

PRINT @a + ' ' + @b + ' ' + @c;

SET @c = 'World';  -- the assignment SILENTLY TRUNCATES the literal string, as precision of @c is 1
PRINT @c;

SET QUOTED_IDENTIFIER OFF;    -- allow double-quotes around string literals
PRINT 'Goodbye';
PRINT "Goodbye";
PRINT e'H\u00e9l\u00e8ne';    -- RSQL syntax

-- if precision is omitted in a CAST, the default precision is 30
PRINT CAST('abcdefghijABCDEFGHIJabcdefghijXYZ' AS VARCHAR); -- default precision is 30

The result is:

Hello O'Hara x
W
Goodbye
Goodbye
Hélène
abcdefghijABCDEFGHIJabcdefghij      <--- truncated to 30 bytes