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 

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

WHILE @b<1000


IF (@a%@b=0)

BEGIN SET @Count=@count+1


SET @b=@b+1;


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


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






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


SET @a=@a+1; 

PRINT @PrimeNumberList


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

SQL Basics TutorialSQL Advance TutorialSSRSInterview Q & A
SQL Create tableSQL Server Stored ProcedureCreate a New SSRS Project List Of SQL Server basics to Advance Level Interview Q & A
SQL ALTER TABLESQL Server MergeCreate a Shared Data Source in SSRSSQL Server Question & Answer Quiz
SQL DropSQL Server PivotCreate a SSRS Tabular Report / Detail Report
..... More.... More....More
Power BI TutorialAzure TutorialPython TutorialSQL Server Tips & Tricks
Download and Install Power BI DesktopCreate an Azure storage accountLearn Python & ML Step by stepEnable Dark theme in SQL Server Management studio
Connect Power BI to SQL ServerUpload files to Azure storage containerSQL Server Template Explorer
Create Report ToolTip Pages in Power BICreate Azure SQL Database ServerDisplaying line numbers in Query Editor Window

 7,096 total views,  1 views today

Leave a Reply

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