简体   繁体   中英

How to apply where condition in query which is stored in other table MySQL

I have requirement where i will fetch where condition stored in other table which can be like id > 10 or amount < 100 .

I am using Stored Procedure to perform some task in which i am retrieving this where condition and using it to insert some data into table. But it's not working maybe due to apostrophe is being appended at front and end.

set @whereC = (select FilterCondition from SearchLeads where `SearchLeadID` = sid);
INSERT INTO `JTemporary` 
        (`ZipID`,`FirstName`,`LastName`,`MemberSince`,
        `Address1`,`Phone`,`Email`,`CompanyName`,
        `BusPhone`,`Deleted`,`CreatedBy`,`CreateDate`,
        `UpdatedBy`,`UpdateDate`)
  select `ZipCode`,`FirstName`,`LastName`,`AddDate`,
        `AddressLine1`,`HomePhone`,`HomeEmail`,`Employer`,
        `BusinessPhone`,'N',loginUserID,now(),
        loginUserID,now() 
    from membertrans where @whereC;

This isn't working. When i apply directly by copying that condition and putting in place of variable it works, But doesn't work with variable.

How to achieve this?

Here's an example that works on my mysql database.

CREATE DEFINER=`root`@`localhost` PROCEDURE `test`(whereClause varchar(512))
BEGIN
SET @str = concat('SELECT * from mytable where ',whereClause);
PREPARE myquery FROM @str;
EXECUTE myquery;
END

I can call the above passing in whatever where clause I like, eg

call test ('col1 between 5 and 10 and col2=''a bit of text''')

The key here is obviously the SET/PREPARE/EXECUTE, which is what you'll need to do.

I used this question Is it possible to execute a string in MySQL? to derive some of the above, since all my own examples turned out to be in SQL Server.

you have not put any column in where condition to match with select query column FilterCondition . Eg.

set @whereC = (select FilterCondition from SearchLeads where `SearchLeadID` = sid);
INSERT INTO `JTemporary` 
        (`ZipID`,`FirstName`,`LastName`,`MemberSince`,
        `Address1`,`Phone`,`Email`,`CompanyName`,
        `BusPhone`,`Deleted`,`CreatedBy`,`CreateDate`,
        `UpdatedBy`,`UpdateDate`)
  select `ZipCode`,`FirstName`,`LastName`,`AddDate`,
        `AddressLine1`,`HomePhone`,`HomeEmail`,`Employer`,
        `BusinessPhone`,'N',loginUserID,now(),
        loginUserID,now() 
    from membertrans where **filterColumn ** IN (or any other clause) @whereC;

I think that is the issue, Try this may this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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