Skip to content

Instantly share code, notes, and snippets.

@JohnL4
Created May 31, 2024 14:41
Show Gist options
  • Save JohnL4/44816f751fbdf34c43295469c7b0cf8d to your computer and use it in GitHub Desktop.
Save JohnL4/44816f751fbdf34c43295469c7b0cf8d to your computer and use it in GitHub Desktop.
A cute way to build dynamic sql by interpolating a string (#interpolation)
DECLARE @message VARCHAR(MAX) = 'Some {item} with {count} {collection}.';
-- Via https://stackoverflow.com/a/77054331/370611
-- Recursive expression, frowned upon by https://learn.microsoft.com/en-us/sql/t-sql/language-elements/select-local-variable-transact-sql?view=sql-server-ver16#c-antipattern-use-of-recursive-variable-assignment
-- But... it does seem to work.
SELECT @message = REPLACE(@message, SearchText, ReplaceText)
FROM ( VALUES -- Table constructor (literal), anonymous table, essentially.
('{item}', 'text string'),
('{count}', '3'),
('{collection}', 'variables')
) _ (SearchText, ReplaceText); -- "_" is essentially an anonymous table alias, not used elsewhere. The tuple is column names.
select @message;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment