4

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?

0

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

1
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.