SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software SQL Server and T-SQL Development Tutorials
Development resources, articles, tutorials, code samples and tools and downloads for ASP.Net, SQL Server, R Script, Windows, Windows Phone, AWS, SAP HANA and ABAP, like SAP UI5, Screen Personas, etc.

SQL Server 2019 Installation
download SQL Server 2019
download SQL Server 2017
download SQL Server 2016
download SQL Server 2014
download SQL Server 2012

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.

Related SQL Resources

SQL Server Articles

SQL Server 2012

SQL Server Tools

SQL Blog

MS SQL Server Forums

Copyright © 2004 - 2020 Eralper YILMAZ. All rights reserved.
Community Server by Telligent Systems