0

I am going to find gcd of two integer numbers by using SQL stored procedure with recursion query. But I got stuck in a loop and I really don't know why, here is my code:

create or alter procedure sp_gcd 
    @s1 int, @s2 int
as
begin
    if (@s1 % @s2 = 0) 
        print @s2
    else if (@s2 % @s1 = 0) 
        print @s1
    else
        begin           
            while (@s2 % @s1 != 0)
                begin
                     declare @temp int = @s2 % @s1 
                     exec sp_gcd @temp, @s1
                end
            print @s1
        end     
 end
 exec sp_gcd 15,21

And this is the result:

3
3
3
3
3
3
3
3
3
...

I just start working with SQL so I will very much appreciate if anyone could help, thanks a lot.

3
  • 1
    What's your DBMS? Commented Mar 28, 2021 at 3:50
  • 3
    Side note (if this is for SQL Server): you should not use the sp_ prefix for your stored procedures. Microsoft has reserved that prefix for its own use (see Naming Stored Procedures), and you do run the risk of a name clash sometime in the future. It's also bad for your stored procedure performance. It's best to just simply avoid sp_ and use something else as a prefix - or no prefix at all! Commented Mar 28, 2021 at 6:39
  • It is ssms and my teacher told me to add sp_ prefix Commented Mar 29, 2021 at 3:45

1 Answer 1

1

stack calls:

sp_gcd 15 21
sp_gcd 6 15
sp_gcd 3 6
print 3
sp_gcd 3 6
print 3
sp_gcd 3 6
print 3

The reason for this to happen is that the while loop, inside the procedure call sp_gcd 6 15, never reaches the false condition; that is, the condition 15 % 6!=0 is always true.

Sign up to request clarification or add additional context in comments.

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.