We can combine SQL functions and use "LIKE" to filter data searching a string in a column. We are not using RegEx, just simple pattern matching. Here's our practical example.
We are given a table called "CityYear" with a column, "Title" that has this pattern "[city name] ([year])", e.g.;
Title
Los Angeles (2015)
Los Angeles (2016)
Los Angeles (2017)
Los Angeles (2018)
Denver (2015)
Denver (2016)
Denver (2017)
Denver (2018)
Dallas (2015)
Dallas (2016)
Dallas (2017)
Dallas (2018)
Let's say we just want to pull the rows containing data for the current year only (2018 at the time of this post).
The first attempt could look like this:
SELECT Title
FROM CityYear
WHERE Title LIKE '% + YEAR(GETDATE() )+ %'
However this returns no results. This is because we are matching to a string that literally contains "+ YEAR(GETDATE() ) +". Trying the following:
SELECT Title
FROM CityYear
WHERE Title LIKE '%' + YEAR(GETDATE ()) + '%'
Gives us an error: Conversion failed when converting the varchar value '%' to data type int.
SELECT Title
FROM CityYear
WHERE Title LIKE '%' + CAST(YEAR(GETDATE()) as varchar(4)) + '%'
The above query returns exactly what we want:
Title
Los Angeles (2018)
Denver (2018)
Dallas (2018)
The following query narrows down possible variations even more by conforming to the pattern and adding parenthesis to the comparison parameter.
SELECT Title
FROM CityYear
WHERE Title LIKE '%(' + CAST(YEAR(GETDATE()) as varchar(4)) + ')%'
If we want to find the previous year (in this case, 2017), we subtract from the YEAR(GETDATE()) function.
SELECT Title
FROM CityYear
WHERE Title LIKE '%(' + CAST(YEAR(GETDATE()) -1 as varchar(4)) + ')%'
Title
Los Angeles (2017)
Denver (2017)
Dallas (2017)