Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Change the following code so it is a Transact-SQL user defined function that can

ID: 3707573 • Letter: C

Question

Change the following code so it is a Transact-SQL user defined function that can be called using SELECT dbo.GCD(@num1, @num2). Make as few changes as possible. Add parameters as needed to make this work.

CREATE FUNCTION GCD

(
   @num1 INT,
   @num2 INT
)

RETURNS INT

AS

BEGIN

   DECLARE @test INT

   IF ABS(@num1) < ABS(@num2)
       SELECT @test = ABS(@num1),
       @num1 = ABS(@num2),
       @num2 = @test
   ELSE
       SELECT @num1 = ABS(@num1),
       @num2 = ABS(@num2)
   SET @test = @num1 % @num2
   WHILE @test > 0
       SELECT   @num1 = @num2, @num2 = @test, @test = @num1 % @num2
       RETURN @num2
END;
GO

Explanation / Answer

CREATE FUNCTION GCD

(

@num1 INT,

@num2 INT

)

RETURNS INT

AS

BEGIN

DECLARE @test INT

IF @num1 IS NULL OR @num2 IS NULL OR (@num1 = 0 AND @num2 = 0)

RETURN NULL

IF @num1 = 0 OR @num2 = 0

RETURN ABS(@num2) + ABS(@num2)

IF ABS(@num1) < ABS(@num2)

SELECT @test = ABS(@num1),

@num1 = ABS(@num2),

@num2 = @test

ELSE

SELECT @num1 = ABS(@num1),

@num2 = ABS(@num2)

SET @test = @num1 % @num2

WHILE @test > 0

SELECT @num1 = @num2,

@num2 = @test,

@test = @num1 % @num2

RETURN @num2

END

--Return shoul be out side while. Also changes to handle nulls

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote