MySQL turn a JOIN statement into a Stored Procedure or Function?

862 views Asked by At

So I have a JOIN statement that I will be using in multiple places. It essentially finds an IP address and matches it to said location from the intermediate table. I need to pass in two variables - one being the prefix of my database/schema and the other being the IP Address itself.
Therefore used is the CONCAT() function in order to piece it together.

So at the moment I have a procedure that looks something like this:

CREATE DEFINER=`root`@`%` PROCEDURE `LocationFromIp`(
ipAddress VARCHAR(16),
clientComp VARCHAR(32)
)
BEGIN

DECLARE test VARCHAR(255);

SET @networkSql = CONCAT("
SET @Location =
    (SELECT `network`.`Name`
    FROM `", clientComp, "-settings`.`iptable` AS `iptable`
    LEFT JOIN `", clientComp, "-settings`.`network` AS `network`
    ON `network`.`Subnet` = `iptable`.`Subnet`
    WHERE `iptable`.`IP` = '", ipAddress, "'
    LIMIT 1);
");

PREPARE test1 FROM @networkSql;
EXECUTE test1;

SELECT @Location AS `Location`;

It returns the result I want however I don't know how I can use this in a statement.

SELECT `IPAddress` AS CALL LocationFromIp('clientComp', `IPAddress`)
(
    SELECT `IPAddress`
    FROM `clientComp-data`.`tablename`
    WHERE @date > `Date`;
)
GROUP BY `IPAddress`

The above does not work but I hope you can understand my thinking!

So how would I do it?

1

There are 1 answers

0
TSorin On

Why can't you adjust your stored procedure to include all the fields that you need from the very beginning?