Miguel Mas Miguel Mas - 12 days ago 6
SQL Question

sql best way to get rid of leading and trailing characters in a varchar

I have a variable (a varchar) in my procedure that contains something like:

{A6DF61AB-8CBF-4E1C-890B-15A7710C7D9C}


what should I do to have

A6DF61AB-8CBF-4E1C-890B-15A7710C7D9C


(without the '{' and '}') instead?

Always same length and always leading and trailing character

Answer

Substring is going to do this for you. The way this works is it takes the string starting from the 2nd character (excludes the first character) and uses the length of the string itself minus 2 to exclude the final character.

CREATE TABLE #SampleData (StringValue nvarchar(100))
INSERT INTO #SampleData
VALUES 
('{A6DF61AB-8CBF-4E1C-890B-15A7710C7D9C}')

SELECT
    StringValue
    ,SUBSTRING(StringValue,2,LEN(StringValue)-2) NewValue
FROM #SampleData

DROP TABLE #SampleData

Results;

StringValue                             NewValue
{A6DF61AB-8CBF-4E1C-890B-15A7710C7D9C}  A6DF61AB-8CBF-4E1C-890B-15A7710C7D9C