1

how do i go about using Mysql variables inside... Mysql regex?

for example,

SET @my_var = (
SELECT 
year 
FROM blah
LIMIT 1);

SELECT 
foo,
bar
FROM my_table
WHERE date REGEXP @my_var%

also tried... WHERE date REGEXP '@my_var%'

what i'm trying to do is... WHERE date REGEXP '2015%'

2
  • show some sample data Commented Jul 20, 2015 at 11:35
  • You can use datepart function to match condition Commented Jul 20, 2015 at 11:41

2 Answers 2

1

You would use concat:

where col regexp concat(@my_var, '%')

But two things:

  1. Your pattern looks more like a LIKE pattern than a REGEXP pattern.
  2. Do not use LIKE or REGEXP for dates. MySQL has many useful date functions.

So, I think you want:

where year(date) = 2015

or:

where date >= '2015-01-01' and date < '2016-01-01'

The last version is preferred because it can take advantage of an index, if available.

Sign up to request clarification or add additional context in comments.

1 Comment

cheers Gordon, that answered it... where year(date) = @current_year
0

Another way, depending on how organized you want to be...

    SET @var = 101;
    SET @regex = concat("^",@var,"$");

    SELECT * FROM db.table 
    WHERE col REGEXP @regex;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.