Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing variables and messages in T-Sql in SQL Server

I have the following code

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 

For input 5, 10 I get the following type of output:

5
*
1
=
5

I want to modify my code to get the following type of output:

5*1=5

Can anyone help me please?

like image 915
Akshay Gupta Avatar asked Sep 21 '25 02:09

Akshay Gupta


2 Answers

Instead of using different print statements use one print statement and append the symbols. Try this.

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 

Result

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
like image 154
Pரதீப் Avatar answered Sep 22 '25 16:09

Pரதீப்


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

... or use your own "Format" function like this one

print dbo.Format3('{0} * {1} = {2}', 2, 3, 6);
like image 21
Vadim Loboda Avatar answered Sep 22 '25 15:09

Vadim Loboda