使用通配符的带有where子句的字符串中的SQL查找字段

时间:2018-07-25 12:45:04

标签: sql sql-server

我需要一些专家建议!下面是我的表格和我要寻找的where子句。我需要能够选择包含当前日期的所有记录,在下面的where子句中,它将是2018年7月的任何月份。不幸的是,您所看到的数据库中的数据存储在ProjNotes字段的字符串中并且无法更改。

任何向我指出正确方向的帮助将不胜感激!

DECLARE @Table AS TABLE (JCCo int, Job varchar(Max), Phase varchar(Max),ProjNotes varchar(MAX))

Insert Into @Table (JCCo, Job, Phase,ProjNotes)
Select 2,'2959-','20.11.100','11/13/2015 1:40:50 PM by CORDOM\ttest
Added 3 wks 9k to include time thru Dec. 2017.

11/17/2016 2:22:28 PM by COR_DOM\ttest
Added 4 months or 62k for a full time PM thru end of project May-2018.

1/4/2018 10:55:37 AM by COR_DOM\ttestd
Reduced proj. costs by approx. 65k due to PM Staff being consolidated.

7/11/2018 2:45:38 PM by COR_DOM\ttest
Increased proj. costs by approx. 36k due to new PM and previous PM who was the Ops Manager and that cost was being charged to general overhead.'

Select *
From @Table
Where ProjNotes Like ('%7/**/2018%') 

2 个答案:

答案 0 :(得分:3)

使用下划线。下划线表示单个字符。

Select *
From @Table
Where ProjNotes Like ('%7/__/2018%') or ProjNotes Like ('%7/_/2018%')

如果在日期之前始终有空格,请使用以下内容照顾月份1月和2月

Select *
From @Table
Where ProjNotes Like ('% 7/__/2018%') or ProjNotes Like ('% 7/_/2018%') or ProjNotes Like ('% _7/__/2018%') or ProjNotes Like ('% _7/_/2018%')

答案 1 :(得分:0)

尝试以下方法应该可以正常工作,只需稍微更改@Tracy添加的内容即可处理1位数或2位数的日期:

DECLARE @Table AS TABLE (JCCo int, Job varchar(Max), Phase varchar(Max),ProjNotes varchar(MAX))

Insert Into @Table (JCCo, Job, Phase,ProjNotes)
Select 2,'2959-','20.11.100','11/13/2015 1:40:50 PM by CORDOM\ttest
Added 3 wks 9k to include time thru Dec. 2017.

11/17/2016 2:22:28 PM by COR_DOM\ttest
Added 4 months or 62k for a full time PM thru end of project May-2018.

1/4/2018 10:55:37 AM by COR_DOM\ttestd
Reduced proj. costs by approx. 65k due to PM Staff being consolidated.

7/11/2018 2:45:38 PM by COR_DOM\ttest
Increased proj. costs by approx. 36k due to new PM and previous PM who was the Ops Manager and that cost was being charged to general overhead.'
union
select 3,'2959-','20.11.100','blah blah 7/1/2018 blah blah '


Select *
From @Table
Where ProjNotes Like ('%7/__/2018%') 
    or ProjNotes Like ('%7/_/2018%')