Using Modulus to Solve a Problem of If a Number is Divisible by a Number

Imagine this scenario, you required a script that would count to 50 and test each number along the way.

If the number was divisible by 2 it would need to print ‘DBA’, if it was divisible by 5 it would print ‘Fire’

If by both then ‘DBAFIRE’

This is a variation of this question.

DECLARE @counter INT

SET @counter = 1

WHILE @counter < 51


	SELECT @counter, 
	CASE WHEN @counter %2 =0 AND @counter %5 = 0 THEN 'DBAFire'  
	WHEN @counter % 2 = 0 THEN 'DBA' 
	WHEN @counter % 5 = 0 THEN 'Fire' 
	ELSE ''

SET @counter = @counter+1

Rob StGeorge
Senior SQL Server Database Administrator residing in Auckland, NZ

Leave a Reply

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