Compare 3 Numbers using SQL Script
This SQL tutorial shows how to compare 3 numbers using SQL script for Transact-SQL beginners.
By changing the below sql codes, developers can easily sort 3 numbers given as variables from biggest to smallest values.
The SQL code first declares variables for input values.
These numeric variables are declared in int data type with variable names @s1, @s2 and @s3.
Then 2 internal int numeric data type variables are declared to hold the biggest and smallest numbers.
These two internal variables are populated when numbers are compared in pairs with each other in order to compare and sort 3 numbers.
After variable declarations for temporarily data storage, instead of creating temp tables, two logical comparison blocks (SQL IF logical compare commands) are executed in order to compare 3 numbers given as parameters.
declare @s1 int, @s2 int, @s3 int
declare @smax int, @smin int
select @s1 = 1, @s2 = 10, @s3 = 2
if @s1 > @s2
select @smax = @s1, @smin = @s2
select @smax = @s2, @smin = @s1
if @s3 < @smin
select @smin = @s3
else if @s3 > @smax
select @smax = @s3
select @smax as 'max', @smin as 'min'
The last SELECT statement returns the max value and min value among these 3 numbers given as input for this SQL tutorial for T-SQL learners.
You can change the @s1, @s2 and @s3 numeric values in order to test SQL script given above.