【问题标题】:How to print a table row wise in SQL Server?如何在 SQL Server 中明智地打印表格行?
【发布时间】:2017-02-13 06:15:56
【问题描述】:

我创建了一个输出数字表的函数,这是我的 UDF 标量函数:

create function fntable(@a int)
returns varchar(250)
as begin
declare @b int, @c varchar(250),@e varchar(50)=''
set @b=1
while (@b<=10)
begin
set @c=@a*@b
set @e=@e+@c
set @b=@b+1
end
return @e
end

它显示我想要的,但据我所知,它在一行中显示结果。我想在多行中显示行。我怎样才能做到这一点 ?我想打印一个数字表。

【问题讨论】:

    标签: sql-server tsql stored-functions


    【解决方案1】:

    你需要一个表值函数。按原样使用您的代码,这大致转换为:

    create function fntable(@a int)
    returns @e table(c int)
    as begin
        declare @b int = 1
        while (@b <= 10)
        begin
            insert into @e values (@a * @b)
            set @b += 1
        end
    
        return
    end
    

    但是请注意,在这种特殊情况下,迭代次数是常数 10,整个事情可以在单个查询中内联完成,而无需循环,只需手动扩展循环即可。然后可以将其保存为内联表值函数,进而可以从其他查询中引用。

    create function fntable(@a int)
    returns table as
    return (
        select @a * 1 as c
        union all
        select @a * 2 as c
        union all
        select @a * 3 as c
        union all
        select @a * 4 as c
        union all
        select @a * 5 as c
        union all
        select @a * 6 as c
        union all
        select @a * 7 as c
        union all
        select @a * 8 as c
        union all
        select @a * 9 as c
        union all
        select @a * 10 as c
    )
    

    【讨论】:

    • 是的,我可以,但如果可能的话,我想根据我的代码显示。
    【解决方案2】:

    改变

    set @e=@e+@c
    

    set @e=@e+@c + CHAR(10)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多