简体   繁体   English

在 T-SQL 中比较日期

[英]Compare dates in T-SQL

I have a table with a column date of datatype varchar .我有一个数据类型为varchar的列date的表。 The values are '2022-03-08 07:00',2022-03-08 07:30... .值为'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'在我的存储过程中,我有一个DATE类型的参数,其值为'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' .我想删除时间分量并比较'2022-03-08''2022-3-8' Notice leading zero in month and day numbers.请注意月份和日期数字中的前导零。

TRY_CAST or TRY_CONVERT will convert your string into date and return null if that is not possible. TRY_CASTTRY_CONVERT会将您的字符串转换为日期,如果不可能则返回 null。

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

use right(replicate('0',2)+value,2) that enables you to change a 1 one_digit number to two_digit number ( 1=>01 ).使用right(replicate('0',2)+value,2)使您能够将1 个一位数更改为两位数( 1=>01 )。 use PARSENAME for split and concat for connect strings使用PARSENAME进行拆分,使用concat进行连接字符串

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*/)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM