CREATE PROC dbo.usp_primes @counter BIGINT = 14, -- where to start (don't need anything less, see below) @maxrows BIGINT = 10000000 -- takes about 20 minutes for 10,000,000 AS BEGIN DECLARE @st DATETIME = getdate(); --==== 1. Create and populate a prime numbers table IF OBJECT_ID('idx.fnPrimes') IS NOT NULL DROP FUNCTION idx.fnPrimes; IF OBJECT_ID('idx.prime') IS NOT NULL DROP TABLE idx.prime; CREATE TABLE idx.prime ( N BIGINT NOT NULL, PRIME BIT NOT NULL, TOTAL INT NOT NULL DEFAULT 0, CONSTRAINT pk_cl__idx_prime_N PRIMARY KEY CLUSTERED(N) ); --==== NOTE: I use a schema called idx for my "indexed functions", not required. --==== 2. Create the nonclustered index CREATE NONCLUSTERED INDEX uq_poc__idx_prime__N ON idx.Prime(N) INCLUDE(PRIME); INSERT idx.prime (N,PRIME) VALUES (1,1),(2,1),(3,1),(4,0),(5,1),(6,0),(7,1), (8,0),(9,0),(10,0),(11,1),(12,0),(13,1); --==== 3. Insert primes PRINT CONCAT(CHAR(10),'Inserting primes(',@maxrows,'rows)',CHAR(10),REPLICATE('-',90)); WHILE @counter <= @maxrows BEGIN IF 0 NOT IN (@counter%2,@counter%3,@counter%5,@counter%7,@counter%11,@counter%13) AND NOT EXISTS ( SELECT N FROM idx.prime AS p WHERE p.N >= @counter AND @counter % p.N = 0 ) INSERT idx.prime(N,PRIME) VALUES(@counter,1) ELSE INSERT idx.prime(N,PRIME) VALUES(@counter,0); SET @counter+=1 END; PRINT CONCAT('All Done: ',DATEDIFF(SECOND,@st,GETDATE()),' seconds'); END; GO