Created
May 31, 2024 14:41
-
-
Save JohnL4/44816f751fbdf34c43295469c7b0cf8d to your computer and use it in GitHub Desktop.
A cute way to build dynamic sql by interpolating a string (#interpolation)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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