简体   繁体   English

SQL-如何在哪里搜索但忽略前两个字符

[英]SQL - How to search WHERE but ignore first two characters

I need to perform a date search but the data is a String with the format 我需要执行日期搜索,但数据是具有以下格式的字符串

'dd/mm/yyyy' 'dd / mm / yyyy'

I want to search only for 'mm/yyyy' 我只想搜索“ mm / yyyy”

For example I want all records that have '07/2014' regardless of what day? 例如,无论什么日子,我都希望所有具有'07 / 2014'的记录?

I'm sure its something simple just can't figure it out 我敢肯定,简单的事情无法解决

EDIT : It looks like the format is MM/DD/YYY Looks like I got this sorted just used: 编辑 :看起来格式是MM / DD / YYY看起来像我刚使用的排序:

RIGHT(BookedDate,5) = '/2014'
AND LEFT (BookedDate,2) = '7/'

Thanks All :) 谢谢大家:)

If your string is in the format of dd/mm/yyyy always, as in 01/09/2014 you could use right: 如果您的字符串始终采用dd/mm/yyyy格式,如01/09/2014 dd/mm/yyyy日,则可以使用right:

declare @val as varchar(10)
Set @val='1/2/2014'
RIGHT(@val,7)

if you are not sure of the format but know that there is a / you could search for it: 如果您不确定格式,但是知道有/ ,则可以搜索:

declare @val as varchar(10)
Set @val='1/2/2014'
select right(@val,len(@val)-patindex('%/%',@val))   
myfield like '%/07/2014'

Beware, since the wildcard (%) is put at the beginning of the query no indexes (if they exist) will be used. 注意,由于通配符(%)放在查询的开头,因此不会使用任何索引(如果存在)。 This will always be a full table scan. 这将始终是全表扫描。

If you store your date values in character based column, than jyparask's answer is good enough, but if you store it in date/time based column, then use date/time functions or intervals: 如果将日期值存储在基于character的列中, 那么jyparask的答案就足够了,但是如果将其存储在基于date/time的列中,则可以使用日期/时间函数或间隔:

WHERE
  myDateColumn >= '01/07/2014'
  AND myDateColumn < '01/08/2014'

The above WHERE condition means: all values in July, 2014. 上面的WHERE条件意味着:2014年7月的所有值。

这将确保(因为它是一个字符串)如果该值比预期的长,则将始终删除前三个字符。

  SELECT RIGHT(field, LEN(field)-3) FROM database

This feels like a very bad idea. 这感觉是一个非常糟糕的主意。 Most likely there is a ton of optimizations that could be done automatically for your queries by the database if you used Date instead of the String. 如果您使用日期而不是字符串,数据库很可能会对您的查询自动进行大量优化。 This is certainly going to be some kind of bottleneck if your database grows, it would have to ask and parse every single row to find out if it matches your request. 如果您的数据库不断增长,这肯定会成为某种瓶颈,它必须询问并解析每一行以找出它是否与您的请求匹配。

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

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