Given a table with two columns - an integer ID and a text-based string - I want to start with a string value that encodes any number of integers wrapped in curly braces, mixed in with any other valid text characters.

Example: '{1} / {9} ... {12}'

With a single SELECT statement, I want to return a string whereby all the integers (and their wrapping braces) have been replaced with a value derived from my table; specifically, the text value for the row having an ID that matches the number found in the source string.... and any characters outside the curly braces remain untouched.

Here is an example that fails to complete the task:

  replace('{13} {15}','{'+cast(id as varchar)+'}',isNull(display,''))
from testing;

This would return 1 row per row in the testing table. For the row with id value = 13, the '{13}' portion of the string is successfully replaced, but the '{15}' portion is not (and vice versa on row 15).

I imagine creating a function that loops through all testing rows and repeatedly attempts replacements would solve the problem. Be that as it may, a straight-up SQL statement would be preferable to looping.

Example Data

| id |  display          |
|  1 |  Apple            |
|  2 |  Banana           |
|  3 |  Celery           |
|  4 |  Dragonfruit      |
|  5 |  Eggplant         |
|  6 |  Fenugreek        |
|  7 |  Gourd            |
|  8 |  Honeydew         |
|  9 |  Iceberg Lettuce  |
| 10 |  Jackfruit        |
| 11 |  Kale             |
| 12 |  Lemon            |
| 13 |  Mandarin         |
| 14 |  Nectarine        |
| 15 |  Olive            |

Example use cases

select replace('{1} {3}',null,null) 
-- Returns 'Apple Celery'

select replace('{3},{4},{5}',null,null); 
-- Returns 'Celery,Dragonfruit,Eggplant'

select replace('{1} / {9} ... {12}',null,null); 
-- Returns 'Apple / Iceberg Lettuce ... Lemon'

Clearly, the replace keyword does not do the job.

PS. If a solution required the format of the string to change in order to facilitate this, that is an option.

For example: '#1 / #9 ... #12' (to correlate with the earlier example)

In this format, perhaps we could break the string up into a rowset, based on #, take the left characters until we find a non-numeric, join to the testing table based on the numbers taken, replace the # and numbers with the testing table's display value then stuff all those individually modified tokens back into a single string for xml path?

I am using SQL Server 2016 which does not support string_agg. That said, if there is a solution using string_agg, I am still interested in reviewing it.


Here is an example of using a recursive cte to translate the variables

drop table if exists testing;
create table testing (id int, display varchar(16));
insert into testing values (1, 'Apple');
insert into testing values (2, 'Banana');
insert into testing values (3, 'Celery');
insert into testing values (4, 'Dragonfruit');
insert into testing values (5, 'Eggplant');

DROP FUNCTION IF EXISTS dbo.TranslateVariables
CREATE FUNCTION dbo.TranslateVariables
    @StringValue VARCHAR(MAX)


--Common Table Expression for Translation
WITH TranslationTable
AS (
    SELECT FindValue = '{' + convert(varchar(5),id) + '}' ,ReplaceValue = display,ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
    FROM testing
--Recursive CTE to loop through the TranslationTable and replace FindValue with ReplaceValue
,RecursiveCte as
SELECT @StringValue AS StrValue
        SELECT count(*)
        FROM TranslationTable
        ) AS cnt


SELECT replace(StrValue, tt.FindValue, tt.Replacevalue)
    ,cnt - 1
FROM RecursiveCte
JOIN TranslationTable tt
    ON tt.rn = cnt )

FROM RecursiveCte where cnt = 0

--Verify translation
FROM dbo.TranslateVariables('{1} {3}')
OPTION (MAXRECURSION 32767) -- Don't forget to use the maxrecursion option!

 StrValue     | cnt |
| Apple Celery | 0   |

FROM dbo.TranslateVariables('{3},{4},{5}')
OPTION (MAXRECURSION 32767) -- Don't forget to use the maxrecursion option!

| StrValue                    | cnt |
| Celery,Dragonfruit,Eggplant | 0   |
  • For my real world case the lookup values are in a table that will need filtering. As such, I've adapted this function to receive an ID as a parameter, to perform that filtering, as well as the format string. Works as expected. – youcantryreachingme May 3 '19 at 2:26
  • Very nice work. – Paul Evans Jan 23 at 1:54

Assuming you're on a version that supports it (and going off the version in your original fiddle), you can use the native string_split() & string_agg() functions.

declare @id_list varchar(10) = '1,3'; -- for 'Apple,Celery' 
-- set @id_list = '3,4,5'; --for 'Celery,Dragonfruit,Eggplant'

select string_agg(display, ',') as agg
from (
    select t.display 
    from testing t
    cross apply string_split(@id_list,',') ss 
    where try_cast(ss.[value] as int) = t.id
) x;

The preceding example assumes you've ditched the curly braces on the way in and it's just a comma-separated list of numbers. If you want to keep the curly braces on the way in, you should try to enforce that it's coming in as well-formed JSON and use some of the native JSON functions for parsing it. The key bits on the above are:

  1. provide an array of [Id]s to...
  2. filter down to only those testing.displays you want and then...
  3. ...feed that text array in to string_agg()

Given the clarification that you're on 2016, and that string_agg() only becomes available in 2017, you can still use string_split() to create the array as needed and use one of the legacy approaches that work around the absence of string_agg() as you mention considering in the OP. For example:

select stuff(agg,1,1,'') as agg_trim_first_comma
from (
    select stuff(x.display,1,0,'') 
    from (
        select ',' + t.display 
        from testing t
        cross apply string_split('1,3',',') ss 
        where try_cast(ss.[value] as int) = t.id
    ) x (display )
    for xml path('')
) y (agg);
  • Thanks Peter. Sorry - I should have specified I'm on SQL Server 2016 (have added the tag) and made clearer that any characters outside the curly braces must remain untouched. In other words, the statement is replacing parameter placeholders within the string, with values. – youcantryreachingme May 2 '19 at 9:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.