Home > Software engineering >  Compare dates in T-SQL
Compare dates in T-SQL

Time:03-09

I have a table with a column date of datatype varchar. The values are '2022-03-08 07:00',2022-03-08 07:30 ... .

In my stored procedure I have a parameter of type DATE and with a value '2022-3-8'

DECLARE @d DATE = '2022-3-8'

SELECT *, r.date AS date, @d AS d 
FROM Readings AS r
WHERE CONVERT(VARCHAR, r.date, 23) = @d

How can I compare these two? I get this error:

Conversion failed when converting date and/or time from character string.

I would like to remove time component and compare '2022-03-08' vs '2022-3-8'. Notice leading zero in month and day numbers.

CodePudding user response:

TRY_CAST or TRY_CONVERT will convert your string into date and return null if that is not possible.

SELECT *, TRY_CAST(r.date AS DATE) as date, @d AS d
FROM Readings r
WHERE TRY_CAST(r.date AS DATE) = @d

Example:

DECLARE @d DATE = '2022-3-8';
WITH Readings AS 
(
    SELECT '2022-03-08 07:00' AS date  
    UNION ALL 
    SELECT '2022-03-08 07:30'
    UNION ALL
    SELECT '2022-03-06 17:30' --will be false
    UNION ALL
    SELECT '2022-02-31 07:30' --invalid string
)
SELECT r.date as OriginalString
, TRY_CAST(r.date AS DATE) as CastDate
, TRY_CONVERT(DATE,r.date,23) as ConvertDate
, @d AS d
, CASE WHEN TRY_CAST(r.date AS DATE) = @d THEN 1 ELSE 0 END AS Matched
FROM Readings r

CodePudding user response:

use right(replicate('0',2) value,2) that enables you to change a 1 one_digit number to two_digit number(1=>01). use PARSENAME for split and concat for connect strings

DECLARE @d DATE = '2022-3-8'

SELECT Concat(( Parsename(Replace(@d, '-', '.'), 3) )/*year*/, '-', RIGHT(
              Replicate('0', 2)   ( Parsename(Replace(@d, '-', '.'), 2) ), 2)
       /*month*/,
              '-', RIGHT(Replicate('0', 2)   ( Parsename(Replace(@d, '-', '.'),
                                               1) ), 2
                   )/*day*/) as d

or in your query

DECLARE @d DATE = '2022-3-8'

SELECT *,
       r.date
       AS date,
       ,@d
FROM   readings AS r
WHERE  CONVERT(VARCHAR, r.date, 23) = 
Concat(( Parsename(Replace(@d, '-', '.'), 3) )/*year*/, '-', RIGHT(
       Replicate('0', 2)   ( Parsename(Replace(@d, '-', '.'), 2) ), 2)/*month*/,
       '-',
       RIGHT(Replicate('0', 2)   ( Parsename(Replace(@d, '-', '.'), 1) ), 2)
       /*day*/)
  • Related