2

I am new to MySQL Procedures and I am trying to write a search procedure for a table.

CREATE PROCEDURE `Search`(
    IN in_locality VARCHAR(200),
    IN in_type VARCHAR(200),
    IN in_city VARCHAR(200)
)
BEGIN
    SELECT * FROM property_details MRP INNER JOIN property_image MRPI
    ON MRP.basic_id=MRPI.basic_id 
    WHERE ((in_locality = '') or (MRP.locality = in_locality))
      AND ((in_property_type = '') or (MRP.property_type = in_property_type))
      AND ((in_city = '') or (MRP.city = in_city)) 
    GROUP BY MRP.id;
END

Now this procedure is working for:

CALL Search('','','','mumbai');

but not for:

CALL Search('','',''mumbai','pune'');

In normal SQL I could use this query for that:

SELECT * FROM property_details where city in('mumbai','chennai')

But I don't how to do this in a procedure.

1
  • If you want to search for multiple values for cities, this will not work. You have an equality condition. Do you need a procedure for this? Why not just use a query? Commented Jan 7, 2014 at 8:35

1 Answer 1

2

Your CALL examples have got 4 arguments, while your CREATE PROCEDURE statement has only got 3. This is because you are trying to specify multiple cities. For this you can use the FIND_IN_SET function to specify the input parameters as comma-seperated lists (MySQL Docs for FIND_IN_SET)

Instead try this

CREATE PROCEDURE `Search`(
    IN in_locality VARCHAR(255),
    IN in_type VARCHAR(255),
    IN in_city VARCHAR(255)
)
BEGIN
    SELECT 
        *
    FROM property_details MRP INNER JOIN property_image MRPI
    ON MRP.basic_id=MRPI.basic_id 
    WHERE ( in_locality = '' XOR FIND_IN_SET( MRP.locality , in_locality ) )
    AND ( in_property_type = '' XOR FIND_IN_SET( MRP.property_type , in_property_type ) )
    AND ( in_city = '' XOR FIND_IN_SET( MRP.city , in_city ) )
    GROUP BY MRP.id;
END

You can then call this using strings with comma-seperated lists in such as the following examples. I also changed them to XOR's because you don't want it searching for an empty string, and changed all 3 searches to be FIND_IN_SET searches.

CALL Search('','','','mumbai'); 
CALL Search('','','mumbai,pune');
Sign up to request clarification or add additional context in comments.

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.