The T-SQL QUOTENAME Function

The T-SQL QUOTENAME Function: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025.

The QUOTENAME function takes a name and returns it wrapped in delimiters, square brackets by default, so it can be dropped safely into a piece of T-SQL. I use it every time I build dynamic SQL from database, schema, table or index names, and you’ll see it all through my maintenance and reporting scripts. It looks trivial, but it does one job that hand-written brackets don’t: it escapes the closing delimiter inside the name.

What the QUOTENAME function does

The syntax is QUOTENAME(character_string [, quote_character]). The first argument is treated as a sysname, so it’s Unicode and limited to 128 characters. The second is optional and defaults to square brackets. The result is nvarchar(258): room for 128 characters, every one of them doubled, plus the two delimiters.

Here’s a quick example with a few awkward names, including one with a closing bracket, one with apostrophes and one that’s too long:

CREATE TABLE #Names
(
    NameId  int IDENTITY(1,1) PRIMARY KEY,
    RawName nvarchar(200) NOT NULL
);

INSERT INTO #Names (RawName)
VALUES (N'Customer'),
       (N'Order Lines'),
       (N'Sales]Archive'),
       (N'O''Brien''s Data'),
       (REPLICATE(N'x', 129));

SELECT NameId,
       LEFT(RawName, 20)          AS RawName,
       QUOTENAME(RawName)         AS Bracketed,
       QUOTENAME(RawName, '''')   AS SingleQuoted,
       LEN(RawName)               AS NameLength
FROM #Names
ORDER BY NameId;

What comes back:

  • Customer becomes [Customer] and 'Customer'.
  • Order Lines becomes [Order Lines], so the space is no longer a problem.
  • Sales]Archive becomes [Sales]]Archive]. The ] inside the name is doubled, which is exactly what the parser needs.
  • O'Brien's Data stays as it is inside brackets (apostrophes don’t matter there), but with a single quote as the delimiter it becomes 'O''Brien''s Data'.
  • The 129-character name returns NULL for both columns.

The quote characters you can use

The second argument is a single character. SQL Server accepts brackets ([ or ]), a single quote, a double quote, parentheses (( or )), angle brackets (< or >), braces ({ or }) and a backtick. You can pass either half of a pair and get the same result: QUOTENAME(N'ab', ']') still returns [ab].

Anything else, such as a pipe, returns NULL rather than an error. Because the argument is one character, passing '[]' quietly uses only the first character, which happens to work, but I’d write '[' or leave it out.

In practice I only use two: the default brackets for object names, and '''' (a single quote, escaped) when I need a name as a string literal inside the dynamic SQL, for example SELECT ' + QUOTENAME(name, '''') + ' AS DatabaseName.

The common mistake with QUOTENAME

The mistake I see most often isn’t using QUOTENAME wrongly; it’s not using it at all and adding the brackets by hand:

DECLARE @TableName sysname = N'Sales]; DROP TABLE dbo.Audit; --';

-- Hand-made brackets: the ] in the name closes the identifier early
SELECT N'SELECT * FROM [' + @TableName + N']' AS HandBuilt;

-- QUOTENAME doubles the ], so the whole value stays one identifier
SELECT N'SELECT * FROM ' + QUOTENAME(@TableName) AS WithQuotename;

The first string comes out as SELECT * FROM [Sales]; DROP TABLE dbo.Audit; --], which is two statements. The second is SELECT * FROM [Sales]]; DROP TABLE dbo.Audit; --]: one odd but harmless table name that simply won’t be found. Most real names never contain a ], which is why the hand-built version seems fine for years.

The second half of the mistake is using QUOTENAME for values rather than names. Because it returns NULL for anything over 128 characters, wrapping a long comment or a WHERE-clause value in QUOTENAME(@x, '''') makes the whole concatenated string NULL. EXEC (@sql) or sp_executesql with a NULL statement just does nothing, with no error, so the job “succeeds” and nothing happens. For values, pass them as parameters to sp_executesql. QUOTENAME is for identifiers.

Watch out for

  • Multi-part names. QUOTENAME(N'dbo.Customer') gives [dbo.Customer], a single name with a dot in it. Quote each part separately: QUOTENAME(@Schema) + N'.' + QUOTENAME(@Table).
  • NULL in, NULL out. A NULL name, an over-long name or an unsupported quote character all return NULL, and one NULL makes the whole + concatenation NULL. Check @sql IS NULL before you run it, or print it while testing.
  • Double quotes depend on QUOTED_IDENTIFIER. QUOTENAME(@x, '"') only gives you an identifier while QUOTED_IDENTIFIER is ON. Brackets always work, which is why I stick with them; there’s more on that in my T-SQL Reserved Keywords post.
  • It isn’t a general escaping tool. It knows nothing about JSON or LIKE wildcards. For JSON strings see the STRING_ESCAPE function.
  • Use the real names. Take names from sys.databases, sys.schemas or sys.objects rather than from user input where you can. QUOTENAME stops the name breaking out, but it won’t stop someone querying a table they shouldn’t.

Microsoft’s reference page is QUOTENAME (Transact-SQL) on Microsoft Learn. For more of my day-to-day scripts, many of which use QUOTENAME in their dynamic SQL, see the SQL Server DBA Handbook.

This topic came up in the SQLServerCentral Question of the Day: QUOTENAME Behavior.

Clive Roberts DBA