简体   繁体   English

在 SQL Server 表中查找与今天相关的日期时间条目的问题

[英]Problem with finding datetime entries which are related to today in a SQL Server table

I have a table with a varchar column with different values in it.我有一个带有 varchar 列的表,其中包含不同的值。 Some of the values in this column are in fact datetime stamp but written in varchar data type.此列中的某些值实际上是日期时间戳,但以 varchar 数据类型写入。 I wish to find entries which contain datetime AND are related to today.我希望找到包含日期时间且与今天相关的条目。 So, my table is like this:所以,我的表是这样的:

  ID  |  column_x
---------------------
  12  |  apple
  13  |  25.03.2018 14:13:58
  14  |  05.10.2020 10:43:17
  15  |  3620

The following query works以下查询有效

select [ID] ,[column_x],
CAST(CONVERT(DATETIME, [column_x] , 104) AS DATE) the_date
from [my_DB].[dbo].[my_table]
where (ISDATE([column_x])=1)

The result is like this:结果是这样的:

  ID  |       column_x          |  the_date
-------------------------------------------------
  13  |  25.03.2018 14:13:58    | 2018-03-25
  14  |  05.10.2020 10:43:17    | 2020-10-05
  15  |  3620                   | 3620-01-01

Now I want to expand the afformentioned query to find the entries that belong to today (2020.10.05)现在我想扩展上述查询以查找属于今天(2020.10.05)的条目

The following query gives error:以下查询给出错误:

select * from (
select [ID] ,[column_x],
CAST(CONVERT(DATETIME, [column_x] , 104) AS DATE) the_date
from [my_DB].[dbo].[my_table]
where (ISDATE([column_x])=1) 
) s
where
(select CAST(CONVERT(DATETIME, s.[column_x] , 104) AS DATE))=
(SELECT CAST(GETDATE() AS DATE))

The error message is:错误信息是:

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

I can't understand why I get this error while I have already chosen only entries that are datetime according to the SQL itself.我不明白为什么我会收到这个错误,而我已经根据 SQL 本身只选择了日期时间的条目。

More strangely, the following query works fine and prints the output:更奇怪的是,以下查询工作正常并打印输出:

if
(select CAST(CONVERT(DATETIME, '05.10.2020 19:46:19' , 104) AS DATE))=
(SELECT CAST(GETDATE() AS DATE))
print 'condition is fulfileld'

Even replacing the date with the problematic number (3620) doesn't result in error.即使用有问题的数字 (3620) 替换日期也不会导致错误。 Just the condition is not met in that case.在这种情况下,只是不满足条件。

I can't understand why I get that error.我不明白为什么我会收到那个错误。

You can use try_convert() .您可以使用try_convert() . . . . but why not convert the current date to the same format:但为什么不将当前日期转换为相同的格式:

select [ID] ,[column_x]
from [my_DB].[dbo].[my_table]
where left(column_x, 10) = convert(varchar(10), getdate(), 104)

To do the comparison the other way:要以另一种方式进行比较:

where try_convert(date, column_x, 104) = convert(date, getdate())

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

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