How to Compare Time in MS SQL Server?
Here, we are going to see how to Compare Time in SQL Server. In this article, we will be making use of the Microsoft SQL Server as our database.
Here, we will first create a database named “geeks”. After, that we will execute our query on that database.
Creating Database:
CREATE DATABASE geeks;
To use this database:
USE geeks;
Here, we could create two variables of datetime, that we need to compare.
Syntax:
declare @input1 datetime;
declare @input2 datetime;
select @input1 = CONVERT(varchar(20),CONVERT(datetime, 'date and time'), 114)
select @input2 = CONVERT(varchar(20),CONVERT(datetime, 'date and time'), 114)
if @input1 <= @input2
print '@input1 less then @input2'
else
print '@input1 more then @input2'
1. Using pre-defined date and time.
In MS SQL Server the query can be designed to compare two or more datetime variables using just the “if” statements.
Example:
declare @day1 datetime;
declare @day2 datetime;
select @day1 = CONVERT(varchar(20),CONVERT(datetime, '2019-02-11 08:00:00'), 114)
select @day2 = CONVERT(varchar(20),CONVERT(datetime, '2020-02-11 08:00:00'), 114)
if @day1 <= @day2
print '@@day1 less then @@day2'
else
print '@@day1 more then @@day2'
Output :
@@day1 less then @@day2
2. Using GETDATE() to compare with current date and time
The GETDATE() function in SQL can also be used to compare multiple dates.
Example:
declare @day1 datetime;
declare @day2 datetime;
select @day1 = CONVERT(varchar(20),GETDATE(), 114)
select @day2 = CONVERT(varchar(20),CONVERT(datetime, '2019-02-11 08:00:00'), 114)
if @day1 <= @day2
print '@@day1 less then @@day2'
else
print '@@day1 more then @@day2'
Output:
@@day1 more then @@day2
Last Updated :
03 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...