如何在 SQL 服务器中打印 table 行?

How to print a table row wise in SQL Server?

我创建了一个输出数字 table 的函数,这是我的 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

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

您需要一个 table-valued 函数。按原样使用您的代码,这大致转化为:

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,整个事情可以在单个查询中内联完成,而无需通过手动扩展循环来简单地进行循环。然后可以将其保存为 内联 table-valued 函数 ,它又可以从其他查询中引用。

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
)

改变

set @e=@e+@c

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