Wrote 2 handy Json based interpolation functions. One makes use of a dictionary style Json (key, value pairs), the other a Json object containing a property for each substitution.
1) Data as Json object
For example, given the template: 'Hey, {name} is {age}'
, run:
SELECT [res4] = [ccgen].[fn_string_interpolation_object]('Hi, {name} is {age}' ,'{"name":"Alice", "age":24}')
... which returns Hey, Alice is 24
CREATE OR ALTER FUNCTION [CcGen].[fn_string_interpolation_object](
@template NVARCHAR(4000), @data_json NVARCHAR(4000)) RETURNS NVARCHAR(4000) AS
/*
=============================================
C# or Java like string interpolation brought to TSQL.
example - copy to run proc
-----------------------
--property names must match those in template. Same as a dynamic object in C#
SELECT [res4] = [ccgen].[fn_string_interpolation_object]('Hi, {name} is {age}' ,'{"name":"Alice", "age":24}')
-- returns
Hi, Alic is 24
=============================================
*/
BEGIN
SELECT @template = REPLACE(@template ,'{' + [key] + '}' ,[value]) FROM OPENJSON(@data_json);
RETURN @template;
END;
2) Data as Json dictionary
For example, given the template: 'Hey, {name} is {age}'
, run:
SELECT [res2] = [ccgen].[fn_string_interpolation]('Hey, {name} is {age}','{"items":[{"key":"name", "value":"Alice"},{"key":"age", "value":"24"}]}')
... which returns Hey, Alice is 24
CREATE OR ALTER FUNCTION [CcGen].[fn_string_interpolation](
@template NVARCHAR(4000),
@key_value_json NVARCHAR(4000)) RETURNS NVARCHAR(4000) AS
/*
=============================================
C# or Java like string interpolation brought to TSQL.
example - copy to run proc
-----------------------
DECLARE @json NVARCHAR(2048) = N'{
"items": [
{
"key": "A",
"value": "a1"
},
{
"key": "B",
"value": "b2"
},
{
"key": "C",
"value": "c3"
}
]
}';
DECLARE @template NVARCHAR(4000) = 'message:= A:{A}, B:{B}, C:{C}'
select res = ccgen.fn_string_interpolation(@template, @json)
-- returns
formatted 3 = A:a1, B:b2, C:c3
=============================================
*/
BEGIN
SELECT @template = REPLACE(@template ,'{' + [key] + '}' ,[value]) FROM OPENJSON(@key_value_json ,'$.items') WITH ( [key] VARCHAR(200) '$.key', [value] VARCHAR(4000) '$.value' );
RETURN @template;
END;
Tip: The Json takes a little more typing. Modify the code and shorten property names to "k" (key) ,"v" (value) and "d" (items) to make it tiny. Then calling is neater:
SELECT [res2] = [ccgen].[fn_string_interpolation]('Hey, {name} is {age}','{"d":[{"k":"name", "v":"Alice"},{"k":"age", "v":"24"}]}')
Notes:
Naturally this will only work on MSSQL versions that support Json. Also there is no support for escaping. For example it's not possible to have {a} as both a literal and a substitution param. This could be added using escaping but can't warrant the effort since I have no use for the feature.
CONCAT()
function can be used. examples – Evacuate