Function Checking Prime Number in SQL Server

Hello to everyone,

In this article, I will try to give information about the function that checks the prime number in SQL Server.

In SQL Server, in some cases, you may want to check if the number you have is a prime number.

You can easily do this using the function below.

--Creating the function

CREATE FUNCTION fn_isPrime
(
    @number INT
)
RETURNS VARCHAR(50)
AS
BEGIN
    DECLARE @result VARCHAR(50);
    DECLARE @i INT = 2;
    WHILE (@i < @number)
    BEGIN
        IF (@number % @i = 0)
        BEGIN
            SET @result = 'The number entered is not a prime number';
            BREAK;
        END;
        ELSE
        BEGIN
            SET @result = 'The number entered is a prime number';
        END;
        SET @i += 1;
    END;
    RETURN @result;
END;


--Use of the function

SELECT dbo.fn_isPrime(39);

When you create the function and run the above code, you will see the following result.

Function Checking Prime Number in SQL Server

As can be seen, it has been checked whether the number is a prime number or not.

Good luck to everyone in business and life.

239 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!