How the QUOTENAME() Function Works in SQL Server (T-SQL)

In SQL Server, the T-SQL QUOTENAME() function returns a Unicode string with the delimiters added to make the input string a valid SQL Server delimited identifier.

It was designed for quoting databases and their objects.

The function accepts two arguments; the input string (required), and a delimiter character (optional).

Syntax

The syntax goes like this:

QUOTENAME ( 'character_string' [ , 'quote_character' ] )

Where character_string is the input string, and quote_character is an optional argument to specify a character to use as the delimiter. If omitted, brackets are used as the delimiter.

Note that character_string is sysname and is limited to 128 characters. Inputs greater than 128 characters return NULL.

Valid delimiters (for the optional quote_character argument) are:

  • ` (backtick)
  • ' (single quotation mark)
  • " (double quotation mark)
  • [] (left or right bracket)
  • () (left or right paranthesis)
  • <> (less than or greater than sign)
  • {} (left or right brace)

Example 1 – Basic Usage

Here’s an example of how it works:

SELECT QUOTENAME('cat[]dog') AS Result;

Result:

+-------------+
| Result      |
|-------------|
| [cat[]]dog] |
+-------------+

Example 2 – Custom Delimiter

Here’s an example of specifying a different delimiter:

SELECT QUOTENAME('cat[]dog', '}') AS Result;

Result:

+------------+
| Result     |
|------------|
| {cat[]dog} |
+------------+

And here’s what happens if we change the middle brackets to curly braces:

SELECT QUOTENAME('cat{}dog', '}') AS Result;

Result:

+-------------+
| Result      |
|-------------|
| {cat{}}dog} |
+-------------+

Example 3 – Invalid Input String

As mentioned, the input string is sysname, and therefore it’s limited to 128 characters. sysname is a system-supplied user-defined data type that is functionally equivalent to nvarchar(128), except that it is not nullable. sysname is used to reference database object names.

Here’s what happens if the input string is too long:

SELECT QUOTENAME('This text is too long to be an input string for this function, because it contains more than 128 characters - too long for sysname.') AS Result;

Result:

+----------+
| Result   |
|----------|
| NULL     |
+----------+

Example 4 – Invalid Delimiter

Here’s what happens if you specify an invalid delimiter:

SELECT QUOTENAME('cat[]dog', '!') AS Result;

Result:

+----------+
| Result   |
|----------|
| NULL     |
+----------+