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
Development resources, articles, tutorials, code samples, tools and downloads for ASP.Net, SQL Server, Reporting Services, T-SQL, Windows, AWS, SAP HANA and ABAP


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
else
 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'
Code

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.



SQL Server

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


Copyright © 2004 - 2021 Eralper YILMAZ. All rights reserved.