Wednesday, December 25, 2024

SQL Server QUOTENAME() Function

 The QUOTENAME() function in SQL Server is used to add delimiters around a string, typically used to safely handle object names (like table, column, or database names) in SQL queries. This helps avoid conflicts with reserved keywords or special characters in object names.

Syntax:

QUOTENAME(string, delimiter)
  • string: The string to be enclosed in delimiters.
  • delimiter: Optional. The character used to enclose the string. The default delimiter is a square bracket ([]), but you can specify a different delimiter, such as a double quote (").

Example 1: Using the default square brackets

SELECT QUOTENAME('myTable');

Output:

[myTable]

Example 2: Using a custom delimiter

SELECT QUOTENAME('myTable', '"');

Output:

"myTable"

Example 3: Handling reserved keywords

If an object name is a reserved keyword, the QUOTENAME() function will ensure it's treated as an identifier.

SELECT QUOTENAME('select');  -- 'select' is a reserved keyword

Output:

[select]

Example 4: With special characters

If the string contains special characters (e.g., spaces or punctuation), QUOTENAME() will still enclose it properly:

SELECT QUOTENAME('my table');

Output:

[my table]

This function is particularly useful in dynamic SQL to ensure the correct handling of identifiers.

No comments:

Post a Comment