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.
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.