How to Remove Quotes of QUOTENAME? – Interview Question of the Week #235

Question: How do you remove the brackets added by QUOTENAME? PARSENAME(value, 1) worked for the simple names in the original example. It is an identifier parser, however, not a general-purpose undo function for every string.

An opened pea pod lies beside its unwrapped peas

A reader followed my QUOTENAME and custom quote character example and updated stored product names. Every name now had brackets around it. The next question was how to get those names back.

Original product names were saved with bracket delimiters
The original bracketed product-name values.
SELECT PARSENAME(Name, 1) AS Name
FROM Production.Product;
Original simple product names after PARSENAME removes identifier brackets
The historical capture demonstrates the original simple values. Its grid header differs from the displayed alias, but the name values match the expression.

Check the limits before updating data

SELECT q.QuotedValue, PARSENAME(q.QuotedValue, 1) AS ParsedName,
       REPLACE(SUBSTRING(q.QuotedValue, 2, LEN(q.QuotedValue)-2),
               N']]', N']') AS UnwrappedValue
FROM (VALUES (QUOTENAME(N'Adjustable Race')),
             (QUOTENAME(N'Part]A')), (QUOTENAME(N''))) AS q(QuotedValue);

QUOTENAME normally surrounds a value with brackets and doubles embedded closing brackets. PARSENAME parses SQL object-name parts and returns NULL for an invalid or empty identifier. Thus [] does not round-trip an empty string through PARSENAME.

The UnwrappedValue expression removes one known bracket pair and reverses doubled closing brackets, including the empty-string case. It is appropriate here only because every input in this small test was produced by default-bracket QUOTENAME. Don’t apply it blindly to mixed strings, other quote characters or values that weren’t wrapped this way.

QUOTENAME accepts at most 128 input characters. If an earlier update saved NULL after longer values were passed to it, no unwrapping function can recover those lost values. Use the original data or a backup.

Preview the old and proposed values, verify which rows were changed and preserve a backup before correcting a stored column. My quick answer solved that reader’s simple case; those checks determine whether it solves yours.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Function, SQL Scripts, SQL Server, SQL String
Previous Post
Can an Index Reduce Performance of SELECT Query? – Interview Question of the Week #234
Next Post
How to Write in Text File from T-SQL in SQL Server? – Interview Question of the Week #236

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.