Question

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.

Was it helpful?

Solution

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');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top