Open In App

How to Print Prime Numbers in MS SQL Server?

In this article, we are going to print Prime numbers using MS SQL. Here we will be using 2 while loops statement for printing prime numbers.

 Steps 1: First we will DECLARE a variable I with initial value 2.



Query:

DECLARE @I INT=2

Step 2: Then we will DECLARE a variable PRIME with an initial value of 0 (this will set the value of PRIME).



Query:

DECLARE @PRIME INT=0

Step 3: Table Definition 

We will create a temporary table variable that will hold prime numbers (using DECLARE and TABLE keywords).

Query:

DECLARE @OUTPUT TABLE (NUM INT)

Step 4: Now we will use nested while loop, same as we write a program for prime numbers.

Query:

DECLARE @I INT=2
DECLARE @PRIME INT=0
DECLARE @OUTPUT TABLE (NUM INT)
WHILE @I<=100
BEGIN
    DECLARE @J INT = @I-1
    SET @PRIME=1
    WHILE @J>1
    BEGIN
        IF @I % @J=0
        BEGIN
            SET @PRIME=0
        END
        SET @J=@J-1
    END
    IF @PRIME =1
    BEGIN
        INSERT @OUTPUT VALUES (@I)
    END
    SET @I=@I+1
END
SELECT * FROM @OUTPUT

Explanation:

Query:

INSERT @OUTPUT VALUES (@I)

Step 5:  Suppose that  I have an initial value of 4, i.e I = 4.

Output: Below output for I<=100 which means it will print prime numbers from 2 to 100.

 

Article Tags :
SQL