SQL QUOTENAME function
Turns a string into a delimited identifier: QUOTENAME('Order Details') gives [Order Details]. Built for dynamic T-SQL, where raw names break parsing.
- Catégorie
- Strings
- Returns
string- In this category
- 60 of 172
Syntaxe
QUOTENAME(name [, quote_character])
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Oui | Supported under this name. |
| PostgreSQL | Different name or syntax | quote_ident(name) adds double quotes when needed |
| MySQL | Not built in | No built-in equivalent. |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Not built in | No built-in equivalent. |
Exemples
SQL Server
SELECT QUOTENAME('Order Details') AS id; -- [Order Details]
SQL Server
SELECT QUOTENAME('weird]name') AS q; -- [weird]]name]
SQL Server
DECLARE @table sysname = N'Order Details'; DECLARE @sql nvarchar(max) = N'SELECT * FROM ' + QUOTENAME(@table) + N' WHERE id = @id'; EXEC sp_executesql @sql, N'@id int', @id = 7;
Bon à savoir
- Embedded closers are doubled, not escaped: QUOTENAME('weird]name') gives [weird]]name], which parses back correctly.
- The optional second argument picks the wrapper: ']' (default), '"', '''' and a few bracket pairs. QUOTENAME(s, '''') builds a string literal, doubling embedded quotes.
- Input longer than 128 characters returns NULL, silently. That matches the sysname limit for identifiers, but it also means QUOTENAME cannot quote longer strings for other uses.
- It never validates that the object exists; it only makes the name parseable. Permission checks still apply to the dynamic statement.
Questions about QUOTENAME
Why use QUOTENAME instead of just adding brackets?
A name containing ] or reserved words breaks hand-bracketed dynamic SQL. QUOTENAME doubles the closers and handles reserved words for you.
Does QUOTENAME prevent SQL injection?
For identifiers, yes when paired with typed parameters for values. It only makes names parseable. Never concatenate user input as values; sp_executesql parameters do that.
Is there a QUOTENAME in MySQL or PostgreSQL?
Not by that name. PostgreSQL's quote_ident() does the same job with double quotes, adding them only when needed. MySQL's sys schema has sys.quote_identifier(), which wraps a name in backticks and doubles embedded ones.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.