简体   繁体   English

SQL编号通配符问题

[英]SQL number Wildcard issue

I'm trying to add a wildcard to my date select query so i only pull the day not time.我正在尝试在我的日期 select 查询中添加一个通配符,所以我只拉日期而不是时间。 Ie 2021-03-11 17:54:30.123.即 2021-03-11 17:54:30.123。 I thought a number could be substituted for a #.我认为可以用数字代替#。

select AID, LocalCoAltIn,LocalCoAltOut,EventTime
from EXCDS.dbo.WKS_LOG_VIEW
where EventTime like '2021-03-11 ##:##:##:###';

My query is returning no values even though they are in the table.即使它们在表中,我的查询也没有返回任何值。 Thanks.谢谢。

No: Don't use strings!不:不要使用字符串! One method is to convert to a date:一种方法是转换为日期:

select AID, LocalCoAltIn,LocalCoAltOut,EventTime
from EXCDS.dbo.WKS_LOG_VIEW
where convert(date, EventTime) = '2021-03-11';

Another method is to use a range:另一种方法是使用范围:

where EventTime >= '2021-03-11' and
      EventTime < '2021-03-12'

The LIKE operator in most flavors of SQL only support _ and * wildcards (matching any one single, or multiple characters). SQL 的大多数风格中的LIKE运算符仅支持_*通配符(匹配任何一个或多个字符)。 Gordon has given you a better approach, but if you wanted to fix your current query on SQL Server you could try: Gordon 为您提供了更好的方法,但如果您想修复 SQL 服务器上的当前查询,您可以尝试:

SELECT AID, LocalCoAltIn, LocalCoAltOut, EventTime
FROM EXCDS.dbo.WKS_LOG_VIEW
WHERE EventTime LIKE '2021-03-11 [0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9][0-9]';

SQL Server extended the LIKE operator to accept a few extra things, such as character classes. SQL 服务器扩展了LIKE运算符以接受一些额外的东西,例如字符类。 Here [0-9] inside LIKE would match any single digit. LIKE中的[0-9]将匹配任何单个数字。

Not sure that like operator would work for date as you want, but you still have few options.不确定like运算符是否可以按您的意愿工作,但您仍然没有什么选择。 Use DATEPART function to retrieve year\month\etc and compare it with exact value that you need使用DATEPART function 检索 year\month\etc 并将其与您需要的确切值进行比较

select AID, LocalCoAltIn,LocalCoAltOut,EventTime from EXCDS.dbo.WKS_LOG_VIEW where DATEPART(year,EventTime) = 2021 AND DATEPART(month,EventTime) = 3 AND DATEPART(day,EventTime = 11);

Or use Gordon Linoff suggestion if you dont care about exact date part and only need to compare entire date without time或者如果您不关心确切的日期部分并且只需要比较整个日期而不需要时间,请使用 Gordon Linoff 建议

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

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