Skip to content
Home » Print Prime numbers for any given n number in SQL Server

Print Prime numbers for any given n number in SQL Server

Print prime numbers separated by comma for any given number .




For example, the prime number for value 10, would be 2,3,5,7 these are the prime numbers up-to number 10.

Here is the query:

Following T-SQL code will all print all prime numbers for given input value to variable @inputNumber.

Lets print all prime numbers till 100.

DECLARE @inputNumber INT=100

DECLARE @a INT=2,@b INT=2,@count INT=0,@c INT=0,@PrimeNumberList NVARCHAR(MAX);

WHILE @a<=@inputNumber 
BEGIN

SET @count=0; 
SET @b=2;

WHILE @b<1000

BEGIN

IF (@a%@b=0)

BEGIN SET @Count=@count+1

END

SET @b=@b+1;

END

IF(@count=1 and @c<1)

BEGIN

SET @PrimeNumberList=CAST(@a AS NVARCHAR(MAX));
SET @c=@c+1;

END

ELSE

BEGIN

IF(@count=1)

BEGIN

SET @PrimeNumberList=@PrimeNumberList+','+CAST(@a AS NVARCHAR(MAX));

END

END
SET @a=@a+1; 
END

PRINT @PrimeNumberList

 

As you can see the below output, it prints all prime numbers till 100.




 

Loading

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.