String.Format like functionality in T-SQL?

后端 未结 13 1942
滥情空心
滥情空心 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:33

    take a look at xp_sprintf. example below.

    DECLARE @ret_string varchar (255)
    EXEC xp_sprintf @ret_string OUTPUT, 
        'INSERT INTO %s VALUES (%s, %s)', 'table1', '1', '2'
    PRINT @ret_string
    

    Result looks like this:

    INSERT INTO table1 VALUES (1, 2)
    

    Just found an issue with the max size (255 char limit) of the string with this so there is an alternative function you can use:

    create function dbo.fnSprintf (@s varchar(MAX), 
                    @params varchar(MAX), @separator char(1) = ',')
    returns varchar(MAX)
    as
    begin
    declare @p varchar(MAX)
    declare @paramlen int
    
    set @params = @params + @separator
    set @paramlen = len(@params)
    while not @params = ''
    begin
        set @p = left(@params+@separator, charindex(@separator, @params)-1)
        set @s = STUFF(@s, charindex('%s', @s), 2, @p)
        set @params = substring(@params, len(@p)+2, @paramlen)
    end
    return @s
    end
    

    To get the same result as above you call the function as follows:

    print dbo.fnSprintf('INSERT INTO %s VALUES (%s, %s)', 'table1,1,2', default)
    

提交回复
热议问题