How to use GROUP_CONCAT in Stored procedure MySQL - mysql

I'm trying to use comma separated values (#job_skills) in another query like as follows in my stored procedure. But it does not work as expected. Amy be it only consider first value from comma separated string. Is there any other way to patch up ?
SELECT GROUP_CONCAT(skillId) as job_skills FROM tbljob_skill as jskl WHERE jskl.jobpostingId = param_jobid INTO #job_skills;
BLOCK6: BEGIN
DECLARE curl_job12 CURSOR FOR SELECT * FROM (SELECT js.jobseekerId FROM tbljobseeker_skill as jss INNER JOIN tbmstjobseeker as js ON (js.jobseekerId = jss.jobseekerId) INNER JOIN tblrecommended_jobseekers_details as rjd ON (js.jobseekerId=rjd.jobseekerId) WHERE jss.skillId IN (#job_skills) AND js.isActive = 'Y' AND js.lat<>0 AND js.lang<>0 AND rjd.sessionid=param_sessionid GROUP BY js.jobseekerId) as m;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET job_done12 = TRUE;
OPEN curl_job12;
read_loop_job12: LOOP
FETCH curl_job12 INTO jsid, miles;
IF job_done12 THEN
LEAVE read_loop_job12;
END IF;
INSERT INTO temp_skills (jobId,skill,jobseekerId) VALUES (param_sessionid,#job_skills,jsid);
IF jsid <> '' THEN
SELECT COUNT(1) INTO check_exists FROM tblrecommended_jobseekers_details WHERE sessionid = param_sessionid AND type = 'match 1 - SKILLS' AND jobseekerId = jsid;
IF check_exists = 0 THEN
START TRANSACTION;
INSERT INTO temp_jobseekers_scores (jobseekerId,score,type,miles) VALUES (jsid,score_skills,'match 1',miles);
INSERT INTO tblrecommended_jobseekers_details (jobseekerId,score,type,miles,sessionid) VALUES (jsid,score_skills,'match 1 - SKILLS',miles,param_sessionid);
COMMIT;
END IF;
END IF;
END LOOP;
CLOSE curl_job12;
END BLOCK6;

Generated comma separated values are a SET and treated as a single string when used with IN function. Instead you have to use FIND_IN_SET to compare with other values.
Change your WHERE clause in CURSOR definition as below.
DECLARE curl_job12 CURSOR FOR
SELECT * FROM (
SELECT js.jobseekerId
FROM tbljobseeker_skill as jss
INNER JOIN tbmstjobseeker as js
ON (js.jobseekerId = jss.jobseekerId)
INNER JOIN tblrecommended_jobseekers_details as rjd
ON (js.jobseekerId=rjd.jobseekerId)
-- WHERE jss.skillId IN (#job_skills)
WHERE FIND_IN_SET( jss.skillId, #job_skills )
AND js.isActive = 'Y'
AND js.lat<>0
AND js.lang<>0
AND rjd.sessionid=param_sessionid
GROUP BY js.jobseekerId
) as m;
Refer to Documentation:
FIND_IN_SET(str,strlist)
Returns a value in the range of 1 to N if the string str is in the
string list strlist consisting of N substrings

Related

Select into statement for null or more than one value

I am stuck in plsql , as I have making function in which I have to update a table if only values comes in select into ..
and if not come then not and if multiple comes then have to update and delete for all that values .
In below function if in first select into null value comes then should not goto exception handling should update only CUSTOMER table and only delete from table 3 ,, if one or many values comes then do all update and delete for each value
create or replace FUNCTION FUNCTION_NAME (
from_PARTICIPANT_KEY1 IN NUMBER
)
RETURN
IS
to_participant_key1 NUMBER (11);
BEGIN
SELECT to_participant_key
INTO to_participant_key1
FROM TABLE2
WHERE FROM_PARTICIPANT_KEY = from_PARTICIPANT_KEY1;
UPDATE CUSTOMERS C
SET C.CUSTOMER_STATUS_CD =
NVL (
(SELECT old_status_cd
FROM TABLE1
WHERE PARTICIPANT_UID = from_PARTICIPANT_KEY1
AND participant_cd = 'CUSTOMER'),
C.CUSTOMER_STATUS_CD
)
WHERE C.CUSTOMER_UID = from_PARTICIPANT_KEY1;
UPDATE subscribers C
SET C.STATUS_CD =
NVL (
(SELECT old_status_cd
FROM TABLE1
WHERE PARTICIPANT_UID = to_participant_key1
AND participant_cd = 'SUBSCRIBER'),
C.STATUS_CD
)
WHERE C.account_no = to_participant_key1;
DBMS_OUTPUT.PUT_LINE ('Delete TABLE1 rows');
DELETE FROM TABLE3
WHERE PARTICIPANT_UID = from_PARTICIPANT_KEY1 AND participant_cd = 'CUSTOMER';
DELETE FROM TABLE1
WHERE PARTICIPANT_UID = to_PARTICIPANT_KEY1 AND participant_cd = 'SUBSCRIBER';
COMMIT;
EXCEPTION -- exception handlers begin
WHEN NO_DATA_FOUND THEN -- handles 'division by zero' error
dbms_output.put_line('Customer not found ' || from_PARTICIPANT_KEY1);
WHEN OTHERS THEN -- handles all other errors
dbms_output.put_line('Some other kind of error occurred.');
END;
You can use BULK COLLECT INTO and iterate over collection.
First of all, you have to declare (or use some existing) collection type and create the variable of this type:
TYPE participant_keys is table of number (11);
l_participant_keys participant_keys;
Then, your query will change to:
SELECT to_participant_key
BULK COLLECT INTO to_participant_key1
FROM TABLE2
WHERE FROM_PARTICIPANT_KEY = from_PARTICIPANT_KEY1;
If the query will not return any record then you can check it with COUNT:
if l_participant_keys.COUNT = 0 then
-- update only CUSTOMER table and only delete from table 3
else
FOR I IN l_participant_keys.FIRST .. l_participant_keys.LAST LOOP
--use l_participant_keys(i) do all update and delete for each value
END LOOP;
end if;

AWS RDS MySQL - GROUP_CONCAT returns multiple rows instead of comma separated string

I have a Stored Procedure that takes three parameters, one of which is TEXT and it should contain comma separated values with ids, something like this -> '12345,54321,11111,22222', and this it inserts a row with data for each id in the list. Below is the Stored Procedure:
DELIMITER //
-- Create Stored Procedure
CREATE PROCEDURE MyProcedure(
IN ItemUUID VARCHAR(255),
IN ReceiverIds TEXT,
IN ItemCreated VARCHAR(255)
)
BEGIN
DECLARE strLen INT DEFAULT 0;
DECLARE SubStrLen INT DEFAULT 0;
IF ReceiverIds IS NULL THEN
SET ReceiverIds = '';
END IF;
do_this:
LOOP
SET strLen = LENGTH(ReceiverIds);
INSERT INTO item_receiver (item_uuid, receiver_id, item_created)
VALUES (ItemUUID ,SUBSTRING_INDEX(ReceiverIds, ',', 1),ItemCreated);
SET SubStrLen = LENGTH(SUBSTRING_INDEX(ReceiverIds, ',', 1)) + 2;
SET ReceiverIds = MID(ReceiverIds, SubStrLen, strLen);
IF ReceiverIds = '' THEN
LEAVE do_this;
END IF;
END LOOP do_this;
END//
DELIMITER ;
To get comma separated values with ids, something like this -> '12345,54321,11111,22222' I execute subquery, however, when I call this Stored Procedure I get this error -> Error Code: 1242. Subquery returns more than 1 row
SET group_concat_max_len = 2048;
call MyProcedure('random_test_uuid',(
SELECT CAST(GROUP_CONCAT(receiver_id SEPARATOR ',') AS CHAR) AS receiver_ids FROM receiver
WHERE user_id LIKE (SELECT user_id FROM user WHERE user_name LIKE 'myName')
GROUP BY receiver_id ),
'2017-09-24 23:44:32');
The problem is the subquery. Remove the group by:
SELECT CAST(GROUP_CONCAT(receiver_id SEPARATOR ',') AS CHAR) AS receiver_ids
FROM receiver
WHERE user_id LIKE (SELECT user_id FROM user WHERE user_name LIKE 'myName')
With the group by, you are getting a separate row for each receiver_id. The group_concat() is not doing anything.
Also, the CAST() is unnecessary. And this would typically be written as:
SELECT GROUP_CONCAT(r.receiver_id SEPARATOR ',') AS receiver_ids
FROM receiver r JOIN
user u
ON u.user_id = r.user_id
WHERE u.user_name LIKE 'myName';
If 'myName' is not using wildcards, then = is more appropriate than like.
If receiver_id is not unique in receiver, then you might want to add distinct to the group_concat().

use local variables in mysql IF statement

I modified the statements as below, but still errors at the line with the DECLARE statement.
BEGIN
DECLARE searchresult int(11);
SET searchresult=(Select count(*) from wbsimsynuqsql where SimBase='a cappella');
IF searchresult >0 THEN
Select * from simsyn1sql where BaseID = (Select Distinct BaseID from wbsimsynuqsql where SimBase='a cappella')
ELSE
Select * from simsyn1sql where BaseID = (Select Distinct BaseID from wbsimsynuqsql where SimSyn='a cappella')
END IF;
END
I am using the expression below in PHPMYADMIN with the intent to use it later in a PHP/MySQL application. It gives an error relating to the DECLARE statement in line 1.
I've looked at example declarations in MySQL and I don't see an error, but I'm doing something wrong and would appreciate a correction/suggestion.
DECLARE searchresult int(11);
SET searchresult=(Select count(*) from wbsimsynuqsql where SimBase='a cappella');
IF searchresult >0
{Select * from simsyn1sql where BaseID = (Select Distinct BaseID from wbsimsynuqsql where SimBase='a cappella')}
[ ELSE
{Select * from simsyn1sql where BaseID = (Select Distinct BaseID from wbsimsynuqsql where SimSyn='a cappella')} ]
END IF;
DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.
like inside a CREATE PROCEDURE you can use DECLARE
Your IF statement is missing a THEN
and remove the square brackets ([]) and the curly braces ({})
If your subquery returns more than one BaseID you might have to use IN instead of =
sqlfiddle

Why find_in_set works but IN clause

I have code like this.
DELIMITER $$
CREATE PROCEDURE `sp_deleteOrderData`(orderid BIGINT(11))
BEGIN
DECLARE shipmentnumbers VARCHAR(1000);
DECLARE cartonid VARCHAR(1000);
SELECT GROUP_CONCAT(a_shipmentid) FROM t_shipment WHERE a_orderid = orderid INTO shipmentnumbers;
SELECT GROUP_CONCAT(a_cartonid) FROM t_carton WHERE a_shipmentid IN (shipmentnumbers) INTO cartonid;
SELECT shipmentnumbers;
/*SELECT cartonid; */
END$$
DELIMITER ;
Here shipmentnumbers returns 100020,100021,100022
Ideally cartonid should be returned as 11,12,13
But i get only 11 as cartonid.
But when i use below code i get proper result.
SELECT GROUP_CONCAT(a_cartonid) FROM t_carton WHERE FIND_IN_SET( a_shipmentid, shipmentnumbers ) INTO cartonid;
I wanted to know what exactly is the difference between IN and FIND_IN_SET and hwo di i decide what to use.
IN accepts a list or parameters to search, FIND_IN_SET accepts a string parameter containing a comma-separated list:
SELECT 1 IN (1, 2, 3, 4)
SELECT FIND_IN_SET(1, '1,2,3,4')
If you try to apply IN to a comma-separated string, it will treat it as a single parameter and will match it as a whole:
SELECT 1 IN ('1,2,3,4')
Of course, the string '1' is not equal to the string '1,2,3,4' so the query above returns false.
FIND_IN_SET searches a string inside a set of string separated by a comma.
MySQL FIND_IN_SET
But you don't need to use GROUP_CONCAT to concatenate the rows to be used in the IN clause, try this,
SELECT GROUP_CONCAT(a_cartonid)
FROM t_carton
WHERE a_shipmentid IN
(
SELECT a_shipmentid
FROM t_shipment
WHERE a_orderid = orderid
)
or use JOIN
SELECT GROUP_CONCAT(DISTINCT a.a_cartonid)
FROM t_carton a
INNER JOIN
(
SELECT a_shipmentid
FROM t_shipment
WHERE a_orderid = orderid
) b ON a.a_shipmentid = b.a_shipmentid

No data return after calling the stored procedures with multiple cursors in it

I have a stored procedures with the following code. The reason i use cursor is to join table which something will return NULL value and cause the record to be disappear. By using this method, I am able to get all data without losing any.
The only problem now is that when i try to call the stored precedures, it return
Error Code : 1329
No data - zero rows fetched, selected, or processed
but when i do a manual select * from TMOMain, the table is created and there is data in it but no data from SignUpCur and UnSubCur mean it was not updated.
1st time using mysql stored procedures so there might be something i miss out.
My Code
ROOT:BEGIN
DECLARE pTotal,pShortCode,pSignUp,pUnSub,pJunk,pT INT;
DECLARE pTc NVARCHAR(10);
DECLARE SignTotal,UnSubTotal, JunkTotal INT;
DECLARE pSignTotal,pSignTeamID,pUnSubTotal,pUnSubT,pSignUpS,pUnSubS INT;
DECLARE pSignTeam,pUnSubTeam NVARCHAR(10);
DECLARE no_more_rows BOOLEAN;
DECLARE MoMainCur CURSOR FOR
SELECT COUNT(*) AS GrandTotal,pShort,(CASE WHEN r= 1 THEN 'A'
WHEN r= 2 THEN 'B' WHEN r= 3 THEN 'C' ELSE 'UV' END) AS Team,recvTeamID
FROM tbli
INNER JOIN tblK ON keywordid = rkey
WHERE recvDate >='2011-11-15' AND recvDate < '2011-11-16'
GROUP BY pShort,Team,recvTeamID;
DECLARE SignUpCur CURSOR FOR
SELECT COUNT(*) AS SignUp,(CASE WHEN r= 1 THEN 'A'
WHEN r= 2 THEN 'B' WHEN r= 3 THEN 'C' ELSE 'UV' END) AS Team,
recvTeamID,pShort
FROM tbli INNER JOIN tbl_user ON recvphone = userphone
INNER JOIN tblK ON keywordid = userpublicstatus
WHERE userdatejoined >='2011-11-15' AND userdatejoined < '2011-11-16'
AND recvdate >='2011-11-15' AND recvdate < '2011-11-16'
GROUP BY Team,recvTeamID,pShort;
DECLARE UnSubCur CURSOR FOR
SELECT COUNT(*) AS UnSub,(CASE WHEN r= 1 THEN 'A'
WHEN r= 2 THEN 'B' WHEN r= 3 THEN 'C' ELSE 'UV' END) AS Team,
recvTeamID,pShort
FROM tbliINNER JOIN tbl_user ON recvphone = userphone
INNER JOIN tblK ON keywordid = userpublicstatus
WHERE userdateExpire >='2011-11-15' AND userdateExpire <'2011-11-16'
AND recvdate >='2011-11-15' AND recvdate < '2011-11-16'
GROUP BY Team,recvTeamID,pShort;
DROP TABLE IF EXISTS `TMoMain`;
CREATE TEMPORARY TABLE TMOMain
(GrandTotal INT,ShortCode INT,Team NVARCHAR(10),SignUp INT,UnSub INT, Junk INT, TeamID INT);
OPEN MoMainCur;
-- Main Table
read_loop:LOOP
FETCH MoMainCur INTO pTotal,pShortCode,pTc,pT;
INSERT INTO TMOMain
VALUES
(pTotal,pShortcode,pTc,0,0,0,pT);
END LOOP read_loop;
CLOSE MoMainCur;
-- Insert Signup Details into Main Table
OPEN SignUpCur;
SignUp_Loop:LOOP
FETCH SignUpCur INTO pSignTotal,pSignTeam,pSignTeamID,pSignUpS;
UPDATE TMOMain
SET SignUp = pSignTotal
WHERE Team = pSignTeam AND Shortcode =pSignUpS;
END LOOP SignUp_Loop;
CLOSE SignUpCur;
-- Insert UnSub Details into Main Table
OPEN UnSubCur;
UnSub_Loop:LOOP
FETCH UnSubCur INTO pUnSubTotal,pUnSubTeam,pUnSubT,pUnSubS;
UPDATE TMOMain
SET UnSub = pSignTotal
WHERE Team = pUnSubTeam AND pShort = pUnSubShortCode;
END LOOP UnSub_Loop;
CLOSE UnSubCur;
SELECT * FROM TMOMain;
END$$
Please try this out:
Add this declaration once (at the top):
DECLARE curIsDone INT DEFAULT FALSE;
Then after you declare your cursor add this:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET curIsDone = TRUE;
After your FETCH commands and before the actions you intend to perform:
IF curIsDone THEN
LEAVE read_loop;
END IF;