Question

Here is my stored function which get the full address from multiple tables

DELIMITER $$

CREATE FUNCTION `get_Address` (Id INT)
RETURNS varchar (250)
BEGIN
DECLARE address varchar (250);

DECLARE state varchar (250);
DECLARE gov varchar (250);
DECLARE city varchar (250);
DECLARE hood varchar (250);
DECLARE street varchar (250);
DECLARE building varchar (250);
DECLARE floor varchar (250);

declare cr1 cursor FOR
SELECT 
    s.state_Name,
    g.governorate_Name,
    c.city_Name,
    h.hood_Name,
    st.street_Name,
    a.address_Building,
    a.address_Floor
FROM
    addresses AS a
        INNER JOIN
    states AS s ON s.state_Id = a.state_Id
        INNER JOIN
    governorates AS g ON g.governorate_Id = a.governorate_Id
        INNER JOIN
    cities AS c ON c.city_Id = a.city_Id
        INNER JOIN
    hoods AS h ON h.hood_Id = a.hood_Id
        INNER JOIN
    streets AS st ON st.street_Id = a.street_Id
WHERE
    a.address_Id = Id;

OPEN cr1;

FETCH cr1 INTO state, gov, city , hood , street, building ,floor;

CLOSE cur1;
RETURN address;
END

i need to get something like this

address = state + gov + city + hood + street + building + floor;

i need to return all the result set and create the full address with PHP or loop the result and create the full address in MYSQL and return a varchar

Was it helpful?

Solution

You cannot return a result set in MySQL as we don't have any such datatype available.

You can use

concat_ws(" ",state , gov , city , hood , street , building , floor) as address 

directly in the query if you need it for once.

If you going to use this several times, well better to make a summary table


But here could be another solution:
1) Create a temp table
2) Fetch the result and fed it inside to temp table
3) Call the tmp table for the address

here is what I mean:

DELIMITER $$
DROP PROCEDURE IF EXISTS get_Address$$
CREATE PROCEDURE `get_Address` (IN Id INT)
BEGIN
  CREATE TABLE tmp_address(ID INT,address VARCHAR(255));

  INSERT INTO tmp_address
  SELECT 
    a.address_Id,
    CONCAT_WS(" ",s.state_Name,
        g.governorate_Name,
        c.city_Name,
        h.hood_Name,
        st.street_Name,
        a.address_Building,
        a.address_Floor) as address
  FROM
    addresses AS a
        INNER JOIN
    states AS s ON s.state_Id = a.state_Id
        INNER JOIN
    governorates AS g ON g.governorate_Id = a.governorate_Id
        INNER JOIN
    cities AS c ON c.city_Id = a.city_Id
        INNER JOIN
    hoods AS h ON h.hood_Id = a.hood_Id
        INNER JOIN
    streets AS st ON st.street_Id = a.street_Id
  WHERE
    a.address_Id = Id;

END$$
DELIMITER ;

Hope this help! :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top