在 SQL 服务器中的 T-Sql 中打印变量和消息

Printing variables and messages in T-Sql in SQL Server

我有以下代码

create procedure math_table1(@num int, @i int)
as
begin
    declare @b int
    set @b = 1 
    while (@b <= @i)
    begin
        print @num 
        print '*'
        print @b 
        print '='
        print  @num * @b;
        set @b = @b + 1;
    end
end 

对于输入 5, 10 我得到以下类型的输出:

5
*
1
=
5

我想修改我的代码以获得以下类型的输出:

5*1=5

有人能帮帮我吗?

不要使用不同的 print 语句,而是使用一个 print 语句并附加 symbols。试试这个。

ALTER PROCEDURE Math_table1 (@num INT,
                             @i   INT)
AS
  BEGIN
      DECLARE @b INT
      SET @b=1

      WHILE( @b <= @i )
        BEGIN
            PRINT CONVERT(VARCHAR(10), @num) + '*'
                  + CONVERT(VARCHAR(10), @b) + '='
                  + CONVERT(VARCHAR(10), @num*@b);

            SET @b=@b + 1;
        END
  END

EXEC Math_table1 5,10 

结果

5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50
create procedure math_table1 (@num int, @i int)
as
begin   
    declare @r int, @b int = 1;
    while (@b <= @i)
    begin
        set @r = @num * @b;
        raiserror ('%d * %d = %d', 0, 1, @num, @b, @r) with nowait;
        set @b = @b + 1;
    end
end 

PRINT vs RAISERROR

... 或使用您自己的 "Format" 函数,例如 this one

print dbo.Format3('{0} * {1} = {2}', 2, 3, 6);