SQL Server printf

前端 未结 5 1518
臣服心动
臣服心动 2021-02-13 05:19

Is there a printf-like function in Sql Server? I want the same features as the RAISERROR function, but instead of throwing an error, or printing a message, I want to wri

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-13 05:49

    Here's a simple printf procedure using sql_variant data types. Unfortunately, it only works for SQL Server 2008 and above.

    CREATE PROCEDURE dbo.printf
      @string nvarchar(max),
      @p1 sql_variant = null,
      @p2 sql_variant = null,
      @p3 sql_variant = null
    AS
    BEGIN
      declare @str nvarchar(200), @pos int, @type char(1)
      select @str = @string, @pos = 0
    
      --- @p1
      set @pos = CHARINDEX('%', @str, @pos)
      if @pos > 0 and substring(@str, @pos, 2) = '%%'
        set @str = stuff(@str, @pos, 2, coalesce(cast(@p1 as nvarchar(100)),'')) 
    
      --- @p2
      set @pos = CHARINDEX('%', @str, @pos)
      if @pos > 0 and substring(@str, @pos, 2) = '%%'
        set @str = stuff(@str, @pos, 2, coalesce(cast(@p2 as nvarchar(100)),'')) 
    
      --- @p3
      set @pos = CHARINDEX('%', @str, @pos)
      if @pos > 0 and substring(@str, @pos, 2) = '%%'
        set @str = stuff(@str, @pos, 2, coalesce(cast(@p3 as nvarchar(100)),'')) 
    
      print @str
    END
    

    And here are sample invocations:

    exec dbo.printf 'Hello %%', 'World'
    exec dbo.printf 'Hello %%. Today is %% of the month', 'World', 28
    declare @dd datetime; set @dd = getDate()
    exec dbo.printf 'Hello %%. Today''s date is %%', 'World', @dd
    

提交回复
热议问题