mpsbhat mpsbhat - 1 year ago 69
SQL Question

MySQL select query with where condition using string variables

Myself trying to pass string variable to where condition in MySQL query as given in this stack overflow answer as given below.

select @start := ' and Id=21';

select * from myTable where 1=1 @start;

So how can I use string variable with where condition in MySQL queries. The variables are set dynamically and the query runs within procedure.

EDIT: I also tried

SET @start = ' Id=21 ';

select * from myTable where (select @start);

But no use.

Answer Source

No you cannot do that. The columns and the condition in the select clause needs to be fixed when you are preparing the select statement.

So you cannot make a dynamic where clause statement like the one you posted. In that example, the values in the column are dynamic not the column names.

The manual says:

A conditional object consists of one or more conditional fragments that will all be joined by a specified conjunction. By default, that conjunction is AND.