String.Format like functionality in T-SQL?

后端 未结 13 1887
滥情空心
滥情空心 2020-12-02 12:54

I\'m looking for a built-in function/extended function in T-SQL for string manipulation similar to the String.Format method in .NET.

相关标签:
13条回答
  • 2020-12-02 13:39

    If you are using SQL Server 2012 and above, you can use FORMATMESSAGE. eg.

    DECLARE @s NVARCHAR(50) = 'World';
    DECLARE @d INT = 123;
    SELECT FORMATMESSAGE('Hello %s, %d', @s, @d)
    -- RETURNS 'Hello World, 123'
    

    More examples from MSDN: FORMATMESSAGE

    SELECT FORMATMESSAGE('Signed int %i, %d %i, %d, %+i, %+d, %+i, %+d', 5, -5, 50, -50, -11, -11, 11, 11);
    SELECT FORMATMESSAGE('Signed int with leading zero %020i', 5);
    SELECT FORMATMESSAGE('Signed int with leading zero 0 %020i', -55);
    SELECT FORMATMESSAGE('Unsigned int %u, %u', 50, -50);
    SELECT FORMATMESSAGE('Unsigned octal %o, %o', 50, -50);
    SELECT FORMATMESSAGE('Unsigned hexadecimal %x, %X, %X, %X, %x', 11, 11, -11, 50, -50);
    SELECT FORMATMESSAGE('Unsigned octal with prefix: %#o, %#o', 50, -50);
    SELECT FORMATMESSAGE('Unsigned hexadecimal with prefix: %#x, %#X, %#X, %X, %x', 11, 11, -11, 50, -50);
    SELECT FORMATMESSAGE('Hello %s!', 'TEST');
    SELECT FORMATMESSAGE('Hello %20s!', 'TEST');
    SELECT FORMATMESSAGE('Hello %-20s!', 'TEST');
    SELECT FORMATMESSAGE('Hello %20s!', 'TEST');
    

    NOTES:

    • Undocumented in 2012
    • Limited to 2044 characters
    • To escape the % sign, you need to double it.
    • If you are logging errors in extended events, calling FORMATMESSAGE comes up as a (harmless) error
    0 讨论(0)
提交回复
热议问题