Search code examples
sqlstringt-sqlinterpolation

SQL Interpolated Strings


Does T-SQL support Interpolated String?

Let's put up this example:

SET @query = 'SELECT ' + @somevariable + ' FROM SOME_TABLE'

I want to be able to do something like that:

SET @query = 'SELECT {@somevariable} FROM SOME_TABLE'

Thanks for the answers!


Solution

  • Giving the credits to @j.f.sebastian for pointing out these solutions. Sadly xp_sprintf is limited to 254 characters, so that wouldn't be ideal when using long queries. FORMATMESSAGE instead is limited to 2047 characters, so that's good enough in order to run long queries.

    I'll summarize everything in one post for the solutions in order to keep things organized.

    Answer 1:

    Using FORMATMESSAGE it's important to know, that using interpolated string as first the parameter, Its supported only SQL versions 2012 and above, so I'll post 2 answers with FORMATMESSAGE:

    SQL Version >= 2012:

    SET @query = FORMATMESSAGE('SELECT %s FROM SOME_TABLE', @somevariable);
    


    SQL Version < 2012:

    EXEC sp_addmessage 50001, 16, 'SELECT %s FROM SOME_TABLE', NULL, NULL, 'replace'
    SET @query = FORMATMESSAGE(50001, @somevariable)
    


    Answer 2:

    Using xp_sprintf stored procedure is important to note that It's limited to 254 characters, so it won't be a good idea for long queries.

    DECLARE  @query AS VARCHAR(100)
            ,@somevariable as VARCHAR(10) = '[id]'
    EXEC xp_sprintf @query OUTPUT, 'SELECT %s FROM SOME_TABLE', @somevariable