How use UPDATE in CONCAT() of PROCEDURE MySQL - mysql

I try update exist tables via PROCEDURE. But I get an error: MySQL: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= iOS, phone_manufacture = Apple, phone_model = iPhone, os_vers = iOS X.X' at line 1
My Procedure:
BEGIN
DECLARE a, b INT;
DECLARE a1, a2, a3, a4 TEXT;
DECLARE cur1 CURSOR FOR SELECT id FROM z7_group;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET b = 1;
OPEN cur1;
SET b = 0;
SET a1 = "iOS";
SET a2 = "Apple";
SET a3 = "iPhone";
SET a4 = "iOS X.X";
WHILE b = 0 DO
FETCH cur1 INTO a;
IF b = 0 THEN
SET #data_ all_group = (SELECT `myTables` FROM `all_group` WHERE id= a);
SET #s = CONCAT('UPDATE ', #data_ all_group, 'SET `os` = ',a1,', `phone_manufacture` = ',a2,', `phone_model` = ',a3', `os_vers` = ',a4,');
PREPARE stmt3 FROM #s;
EXECUTE stmt3;
END IF;
END WHILE;
CLOSE cur1;
END;

You have two options:
(there is more but I think it is what you want)
Enclose values in single quotes at inicialization:
SET a1 = "'iOS'";
SET a2 = "'Apple'";
SET a3 = "'iPhone'";
SET a4 = "'iOS X.X'";
and fix the sentence:
CONCAT('UPDATE ', #data_all_group, ' SET `os` = ',a1,', `phone_manufacture` = ',a2,', `phone_model` = ',a3,', `os_vers` = ',a4)
The result will be:
UPDATE your_table SET `os` = 'iOS', `phone_manufacture` = 'Apple', `phone_model` = 'iPhone', `os_vers` = 'iOS X.X'
OR: fix the query build:
SET #s = CONCAT('UPDATE ', #data_all_group
, "SET `os` = '" , a1 ,"',"
, "`phone_manufacture` = '",a2,"',"
, "`phone_model` = '",a3,"',"
, "`os_vers` = '",a4,"'");

Related

passing json in stored procedures

I am calling a stored procedure and it is giving a syntax error, I am unable to figure it out. Can anyone help?
"sqlMessage": "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\"billToId\":137,\"shipToId\":137,\"loadingId\":137,\"loadingLocationId\":2,\"billToLocat' at line 1",
It is a JSON that I am passing as a string.
Here's the stored procedure:
drop procedure if exists createRequisition;
DELIMITER $$
CREATE PROCEDURE createRequisition(p_reqBranchId INT,p_unloadingJson JSON,locationsString text,p_quantity FLOAT,
p_expectedDeliveryDate DATE,p_loadingDate DATE,p_refId VARCHAR(255),p_notes TEXT,p_createdBy VARCHAR(255),p_vehicleId INT, p_vehicleName VARCHAR(255),p_isWeb int,p_priority int,p_editId int)
BEGIN
-- call SP_TMS_CreateRequisition()
declare lastReqCode int;
declare d_ReqCode text;
declare d_branchCode text;
declare lastInsert INT;
declare d_branchIdsStr text;
START transaction;
if(p_editId is null) then
BEGIN
SET d_branchCode = (select group_concat(freighterCode) from Freighters join Branches on freighterId = branchFreighterId where branchId = p_reqBranchId);
SET d_branchIdsStr = (select group_concat(branchId) from Branches where branchFreighterId = (select branchFreighterId from Branches where branchId = p_reqBranchId) );
SET lastReqCode = (SELECT if(max(CAST(substring(reqCode,5) AS UNSIGNED))>0,max(CAST(substring(reqCode,5) AS UNSIGNED)),0) FROM Requisitions where find_in_set(reqBranchId,d_branchIdsStr));
set d_ReqCode = (select concat(d_branchCode,lastReqCode+1));
INSERT INTO Requisitions(reqCode,reqBranchId,vehicleId,vehicleName,loadingUnloadingJson,quantity,originalQuantity,deliveryDate,loadingDate,referenceNumber,notes,createdAt,createdBy,updatedAt,reqIsWeb,priority)
VALUES(d_ReqCode,p_reqBranchId,p_vehicleId, p_vehicleName,p_unloadingJson,p_quantity,p_quantity,p_expectedDeliveryDate,p_loadingDate,p_refId,p_notes,NOW(),p_createdBy,NOW(),p_isWeb,p_priority);
set lastInsert = (SELECT LAST_INSERT_ID());
set locationsString = replace(locationsString,'reqId',lastInsert);
set #reqLocationInsert = concat('INSERT INTO RequisitionDetails (requisitionId,billToBranchId,shipToBranchId,loadingBranchId,loadingLocationId,billToLocationId,shipToLocationId,skuId,skuQuantity,skuWeight,requisitionJson) VALUES',locationsString);
PREPARE stmt from #reqLocationInsert;
EXECUTE stmt;
select lastInsert as reqId;
END;
else
BEGIN
UPDATE `Requisitions`
SET
`vehicleId` = p_vehicleId,
`vehicleName` = p_vehicleName,
`loadingDate` = loadingDate,
`referenceNumber` = p_refId,
`notes` = p_notes,
`updatedAt` = now(),
`updatedBy` = p_createdBy,
`priority` = p_priority
WHERE `reqId` = p_editId;
DELETE from RequisitionDetails where requisitionId = p_editId;
set #reqLocationInsert = concat('INSERT INTO RequisitionDetails (requisitionId,billToBranchId,shipToBranchId,loadingBranchId,loadingLocationId,billToLocationId,shipToLocationId,skuId,skuQuantity,skuWeight,requisitionJson) VALUES',locationsString);
PREPARE stmt from #reqLocationInsert;
EXECUTE stmt;
select lastInsert as reqId;
END;
end if;
COMMIT;
END
And the parameters that I am passing is:
call createRequisition(5,null,'(reqId,137,137,137,2,2,2,493,{\"billToId\":137,\"shipToId\":137,\"loadingId\":137,\"loadingLocationId\":2,\"billToLocationId\":2,\"shipToLocationId\":2,\"skuId\":493,\"skuWeight\":30,\"loadingbranchName\":\"New Branch \",\"loadingCompanyName\":\"Teja & Teja Pvt. Ltd\",\"loadingErpCode\":\"WERT\",\"loadingShortName\":\"Kolkata\",\"loadingLongName\":\"West Bengal, India\",\"shipToCompanyName\":\"Teja & Teja Pvt. Ltd\",\"shipTobranchName\":\"New Branch \",\"shipToErpCode\":\"WERT\",\"shipToShortName\":\"Kolkata\",\"shipToLongName\":\"West Bengal, India\",\"billToBranchName\":\"New Branch \",\"billToCompanyName\":\"Teja & Teja Pvt. Ltd\",\"billToErpCode\":\"WERT\",\"billToShortName\":\"Kolkata\",\"billToLongName\":\"West Bengal, India\",\"skuQuantity\":10})',
10,null,'2019-10-18',
'111','Just Do It',
'17',2,
'Open Daala zzz',1,'HIGH',null)

What does "The following query failed" ";"" mean in MySQL?

While trying to update a trigger, MySQL tells me the query ";" failed. How is ";" even a query in MySQL's view is beyond me.
The exact message is:
The following query has failed: ";" MySQL said: #1065 - Query was empty
Here's the new trigger (AFTER INSERT):
BEGIN
DECLARE vIdPlacet VARCHAR(40);
DECLARE vTypeTravaux VARCHAR(32);
DECLARE vEssence VARCHAR(3) DEFAULT '-';
DECLARE vClasseHau VARCHAR(5) DEFAULT '-';
DECLARE vNoMesurag int;
DECLARE new_id_parcelle INT UNSIGNED DEFAULT 0;
DECLARE new_no_microplacette INT UNSIGNED DEFAULT 0;
IF NEW.deleted = 0 THEN
SELECT id_parcelle, no_microplacette
INTO new_id_parcelle, new_no_microplacette
FROM microplacette
WHERE id_microplacette = NEW.id_microplacette;
SELECT travaux, no_mesurag, id__placet
INTO vTypeTravaux, vNoMesurag, vIdPlacet
FROM secteur
LEFT JOIN parcelle ON secteur.id_secteur = parcelle.id_secteur
WHERE id_parcelle = new_id_parcelle;
IF vTypeTravaux = 'inventaire' THEN
SELECT abbreviation INTO vEssence FROM essences WHERE _id = NEW.id_essence;
IF NEW.hauteur_15 = 1 THEN
SET vClasseHau = '15CM+';
END IF;
IF (SELECT COUNT(*) FROM imported_pres_ess WHERE id__placet = vIdPlacet AND
caracteris = '-' AND
classe_hau = vClasseHau AND
essence = vEssence AND
no_mesurag = vNoMesurag AND
no_micro_p = new_no_microplacette) = 0 THEN
INSERT INTO imported_pres_ess (id__placet, caracteris, classe_hau, essence, no_mesurag, no_micro_p)
VALUES (vIdPlacet, '-', vClasseHau, vEssence, vNoMesurag, new_no_microplacette);
END IF;
IF (SELECT COUNT(*) FROM imported_semi_gau WHERE id__placet = vIdPlacet AND
classe_hau = vClasseHau AND
essence = vEssence AND
no_mesurag = vNoMesurag AND
no_micro_p = new_no_microplacette) = 0 THEN
INSERT INTO imported_semi_gau (id__placet, classe_hau, essence, no_mesurag, no_micro_p)
VALUES (vIdPlacet, vClasseHau, vEssence, vNoMesurag, new_no_microplacette);
END IF;
IF NEW.diametre > 0 THEN
SET vClasseHau = 'D2_D8';
ELSE
SET vClasseHau = '-';
END IF;
IF (SELECT COUNT(*) FROM imported_pres_ess WHERE id__placet = vIdPlacet AND
caracteris = '-' AND
classe_hau = vClasseHau AND
essence = vEssence AND
no_mesurag = vNoMesurag AND
no_micro_p = new_no_microplacette) = 0 THEN
INSERT INTO imported_pres_ess (id__placet, caracteris, classe_hau, essence, no_mesurag, no_micro_p)
VALUES (vIdPlacet, '-', vClasseHau, vEssence, vNoMesurag, new_no_microplacette);
END IF;
IF (SELECT COUNT(*) FROM imported_semi_gau WHERE id__placet = vIdPlacet AND
classe_hau = vClasseHau AND
essence = vEssence AND
no_mesurag = vNoMesurag AND
no_micro_p = new_no_microplacette) = 0 THEN
INSERT INTO imported_semi_gau (id__placet, classe_hau, essence, no_mesurag, no_micro_p)
VALUES (vIdPlacet, vClasseHau, vEssence, vNoMesurag, new_no_microplacette);
END IF;
END IF;
END IF;
END
I tried creating the procedure you show, but I don't get any error.
The error about "empty statement" happens when you try to execute a query through the API but the query string is empty.
I can duplicate the error in the mysql client this way:
mysql> set #s = '';
mysql> prepare stmt from #s;
ERROR 1065 (42000): Query was empty
So I suggest you look not at the stored procedure, but whatever code you're executing this from, and check that every time you try to execute a query, that you submit a non-empty string.
It turns out, the trigger I was updating got deleted in the meantime, so I was updating a trigger that didn't exist anymore.
I found out after refreshing the page (the trigger was gone from the trigger list).
I simply recreated the trigger anew and it worked.

SQL Server - Unable to run cursor FETCH statement dynamically stored in variable

I've a cursor which fetch dynamic number of columns because the "SELECT STATEMENT" which I use to declare this cursor is dynamic.
Since I do not know at any point of time, how many columns this cursor will have, I cannot declare fixed number of variables into fetch.
So I have built FETCH statement as dynamic and stored in one #variable... but when i run fetch statement using EXEC sp_executesql
its failing with error ..Must declare the scalar variable "#objcursor".
I know that #objcursor variable is not accessible becasue while sp_executesql run which run on isolate THREAD
is there any way someone can advise, how to handle this code to run without an error?
Here is my T-SQL code:
/* ==== Variable Declaration ==== */
declare #AllValues nvarchar(max)
declare #objcursor as cursor
declare #MonthCount integer
declare
#vsql as nvarchar(max)
,#vquery as nvarchar(max)
,#id as int
,#value as varchar(50)
BEGIN
SELECT #AllValues = CASE
WHEN t.column_id=1 THEN
(COALESCE(#AllValues +'"', '')+ t.name)+'"'
WHEN t.column_id > 1 THEN
(COALESCE(#AllValues + ',"', '') + t.name)+'"'
END
FROM
(
SELECT sc.name, sc.column_id FROM sys.objects o
INNER JOIN sys.columns sc ON o.object_id = sc.object_id
WHERE o.name = 'temp_daywise' AND o.type = 'U' AND (sc.name like '%Curr Yr%' or column_id=1)
) AS t
ORDER BY t.column_id
SET #AllValues='SELECT "'+#AllValues+' FROM dbo.temp_daywise'
set #vquery = #AllValues
set #vsql = 'set #cursor = cursor forward_only static for ' + #vquery + ' open #cursor;'
exec sys.sp_executesql
#vsql
,N'#cursor cursor output'
,#objcursor output
---Handling Dynamic number of columns in a cursor, get the column count first and build FETCH statement dynamically
Select #CurCount=COUNT(*) from sys.columns where object_id in(
SELECT object_id from sys.objects where name = 'dbo.temp_daywise' and type = 'U' )
and (name like '%Curr Yr%');
SET #LoopCount = 1
--here building my fetch statement
SET #fetchsql ='fetch next from #objcursor into #AgreementID'
WHILE #LoopCount <= #CurCount
BEGIN
SET #fetchsql = #fetchsql+','+'#CY_Day'+CONVERT(VARCHAR(2),#LoopCount)
SET #LoopCount = #LoopCount + 1
END
--EXEC #fetchsql
EXEC sp_executesql #fetchsql
while (##fetch_status = 0)
begin
BEGIN
'update ...here something'
END
EXEC #fetchsql
end
close #objcursor
deallocate #objcursor
END
Here is my data and expected resullts:
1) My dynamic cusror will read column name from sys.columns because coulmns are not static that's based on columns count I'm building FETCH statement. following code build cusrsor SELECT statement
SELECT #AllValues = CASE
WHEN t.column_id=1 THEN
(COALESCE(#AllValues +'"', '')+ t.name)+'"'
WHEN t.column_id > 1 THEN
(COALESCE(#AllValues + ',"', '') + t.name)+'"'
END
FROM
(
SELECT sc.name, sc.column_id FROM sys.objects o
INNER JOIN sys.columns sc ON o.object_id = sc.object_id
WHERE o.name = 'temp_daywise' AND o.type = 'U' AND (sc.name like '%Curr Yr%' or column_id=1)
) AS t
ORDER BY t.column_id
SET #AllValues='SELECT "'+#AllValues+' FROM dbo.temp_daywise'
set #vquery = #AllValues
set #vsql = 'set #cursor = cursor forward_only static for ' + #vquery + ' open #cursor;'
exec sys.sp_executesql
#vsql
,N'#cursor cursor output'
,#objcursor output
2) I want to update fetch data into following table for columns Day1...Day31. if cusrsor found 20 columns data will update until CY_Day20.
3) In short, i do not know the cusror retrieving columns at design time so i can't produce fetching variable. Since columns are known at run tiume, i have to build fetch & update statment in while loop as like below:
Note: ignore DECLARE which is on start of the code... but i placed here to get an idea.
DECLARE
#CY_Day1 Numeric(18,2), #CY_Day2 Numeric(18,2), #CY_Day3 Numeric(18,2), #CY_Day4 Numeric(18,2), #CY_Day5 Numeric(18,2),
, #CY_Day7 Numeric(18,2), #CY_Day8 Numeric(18,2), #CY_Day9 Numeric(18,2), #CY_Day10 Numeric(18,2), #PY_Day10 Numeric(18,2), #CY_Day11 Numeric(18,2), #CY_Day12 Numeric(18,2),........ #CY_Day31 Numeric(18,2)
Select #CurCount=COUNT(*) from sys.columns where object_id in(
SELECT object_id from sys.objects where name = 'dbo.temp_daywise' and type = 'U' )
and (name like '%Curr Yr%');
SET #LoopCount = 1
SET #fetchsql ='fetch next from #objcursor into #AgreementID'
SET #updatesql ='UPDATE dbo.TPDD_Report_Monthly_Details SET '
WHILE #LoopCount <= 2
BEGIN
SET #fetchsql = #fetchsql+','+'#CY_Day'+CONVERT(VARCHAR(2),#LoopCount)
SET #updatesql= #updatesql +'CY_Day'+CONVERT(VARCHAR(2),#LoopCount)+' = #CY_Day'+CONVERT(VARCHAR(2),#LoopCount)+',CY_TPDD_Day'+CONVERT(VARCHAR(2),#LoopCount)+' = (#CY_Day'+CONVERT(VARCHAR(2),#LoopCount)+'/1/1),'
SET #LoopCount = #LoopCount + 1
END
SET #updatesql =#updatesql + ' dss_update_time = #v_dss_update_time WHERE AgreementId = #AgreementID and TpddYear=CONVERT(VARCHAR(4),#Current_year)+CONVERT(VARCHAR(4),#Previous_year) and Running_Month = #MonthNo'
--EXEC #fetchsql
PRINT #fetchsql
PRINT #updatesql
---executing FETCH statement
EXEC sp_executesql #fetchsql
while (##fetch_status = 0)
begin
BEGIN
---updating table columns
EXEC sp_executesql #updatesql
END
EXEC #fetchsql
end
close #objcursor
deallocate #objcursor
Finally my cusrsor fetch & udpate statement will looks like below:
fetch next from #objcursor into #AgreementID,#CY_Day1,#CY_Day2,#CY_Day3,#CY_Day4,#CY_Day5,#CY_Day6,#CY_Day7,#CY_Day8,#CY_Day9,#CY_Day10
UPDATE dbo.TPDD_Report_Monthly_Details SET
CY_Day1 = #CY_Day1, CY_TPDD_Day1 = (#CY_Day1/1/1),
CY_Day2 = #CY_Day2, CY_TPDD_Day2 = (#CY_Day2/1/1),
CY_Day3 = #CY_Day3, CY_TPDD_Day3 = (#CY_Day3/1/1),
CY_Day4 = #CY_Day4, CY_TPDD_Day4 = (#CY_Day4/1/1),
CY_Day5 = #CY_Day5, CY_TPDD_Day5 = (#CY_Day5/1/1),
CY_Day6 = #CY_Day6, CY_TPDD_Day6 = (#CY_Day6/1/1),
CY_Day7 = #CY_Day7, CY_TPDD_Day7 = (#CY_Day7/1/1),
CY_Day8 = #CY_Day8, CY_TPDD_Day8 = (#CY_Day8/1/1),
CY_Day9 = #CY_Day9, CY_TPDD_Day9 = (#CY_Day9/1/1),
CY_Day10 = #CY_Day10, CY_TPDD_Day10 = (#CY_Day10/1/1),
dss_update_time = #v_dss_update_time
WHERE AgreementId = #AgreementID
Hope I;m able to present my problem correctly.
I have a good start. You're probably going to have to tweak a few things. I did my best to get it as close as possible as your actual situation. Hope this helps. If you have any questions, let me know.
NOTE I USE THE SAME TABLE NAMES AND DROP THEM.
IF OBJECT_ID('dbo.temp_daywise') IS NOT NULL
DROP TABLE dbo.temp_daywise;
IF OBJECT_ID('dbo.TPDD_report_Monthly_Details') IS NOT NULL
DROP TABLE dbo.TPDD_report_Monthly_Details;
CREATE TABLE dbo.temp_daywise
(
AgreementID CHAR(6),
RunningMonth INT,
[Curr Yr1] VARCHAR(100),
[Curr Yr2] VARCHAR(100),
[Curr Yr3] VARCHAR(100)
);
INSERT INTO temp_daywise
VALUES ('A10001',3,'col1_1','col2_1','col3_1'),
('A10003',3,'col1_2','col2_2','col3_2'),
('A10006',3,'col1_3','col2_3','col3_3'),
('A10008',3,'col1_4','col2_4','col3_4');
CREATE TABLE dbo.TPDD_report_Monthly_Details
(
TpddYear DATE,
AgreementID CHAR(6),
RunningMonth INT,
[CY_Day1] VARCHAR(100),
[CY_Day2] VARCHAR(100),
[CY_Day3] VARCHAR(100)
);
INSERT INTO TPDD_report_Monthly_Details
VALUES ('20131220','A10001',3,NULL,NULL,NULL),
('20131220','A10003',3,NULL,NULL,NULL),
('20131220','A10006',3,NULL,NULL,NULL),
('20131220','A10008',3,NULL,NULL,NULL);
--Now that I've created my versions of your table, here's the actual code
--Variable to hold columns that need to be updated
DECLARE #ColToBeUpdated VARCHAR(MAX);
--Gets your column information for temp_daywise
WITH CTE_temp_daywise_Cols
AS
(
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'temp_daywise'
)
--Now join temp_daywise columns to TPDD_report columns
--QUOTENAME() add's brackets [] around each column
SELECT #ColToBeUpdated = COALESCE(#ColToBeUpdated + ',','') + QUOTENAME(A.COLUMN_NAME) + ' = B.' + QUOTENAME(B.COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS A
INNER JOIN CTE_temp_daywise_Cols B
--The "+1" compensates for difference in ordinal positions
ON A.Ordinal_Position = B.ORDINAL_POSITION + 1
--This makes the table alisaed A to only get columns for TPDD_report
WHERE A.TABLE_NAME = 'TPDD_report_Monthly_Details'
--Don't return AgreementID
AND A.COLUMN_NAME != 'AgreementID'
AND B.COLUMN_NAME != 'AgreementID'
ORDER BY A.ORDINAL_POSITION
--Variable to hold code
DECLARE #sql VARCHAR(MAX);
SELECT #sql = 'UPDATE dbo.TPDD_Report_Monthly_Details
SET ' + #ColToBeUpdated +'
FROM dbo.TPDD_Report_Monthly_Details AS A
INNER JOIN temp_daywise AS B
ON A.AgreementID = B.AgreementID'
--Look at code
--Notice you can join on AgreementID and just set the columns equal to each other
SELECT #sql;
--To execute
--EXEC(#sql)
Results stored in #sql:
UPDATE dbo.TPDD_Report_Monthly_Details
SET [RunningMonth] = B.[RunningMonth],
[CY_Day1] = B.[Curr Yr1],
[CY_Day2] = B.[Curr Yr2],
[CY_Day3] = B.[Curr Yr3]
FROM dbo.TPDD_Report_Monthly_Details AS A
INNER JOIN temp_daywise AS B
ON A.AgreementID = B.AgreementID

Asking about stored function in mysql

drop function if exists rty_check_member_info_status;
DELIMITER $$
--
-- Functions
CREATE DEFINER=root#localhost FUNCTION rty_check_member_info_status(memb_id int,field_name_1 varchar(100),field_name_2 varchar(100),login_member_amount int(11),login_status char(1)) RETURNS char(1) CHARSET latin1
begin
declare fn_field_name_1 varchar(100) ;
declare fn_field_name_2 varchar(100) ;
declare fn_amount_for_profile_visible int(11);
declare fn_return char(1) default 'N';
declare test_field varchar(100);
select field_name_1,field_name_2,amount_for_profile_visible into
fn_field_name_1,fn_field_name_2,fn_amount_for_profile_visible
from member_account_settings inner join tbl_members on member_account_settings.member_auto_id = tbl_members.member_id
where tbl_members.member_id = memb_id ;
if fn_field_name_1 = 'H' Then
set fn_return = 'N' ;
else
if fn_field_name_2 = 'Y' Then
if fn_amount_for_profile_visible = '0' Then
set fn_return = 'Y' ;
else
if login_status = 1 Then
if fn_amount_for_profile_visible > login_member_amount Then
set fn_return = 'N' ;
else
set fn_return = 'Y' ;
end if;
else
set fn_return = 'N';
end if ;
end if;
else
set fn_return = 'Y';
end if ;
end if ;
return fn_return ;
end$$
DELIMITER ;
You're two choices are pretty much generated SQL(normally a bad idea because it's harder to write, debug and document) and using a case statement to select the column based on the name matching a string(which is normally a pretty good solution).
Here's an example of the second, since it's the solution I'd definitely recommend.
SET #test_field1 = "last_name_display_status" ;
SET #test_field2 = "last_name_display_for_other_partcpnt" ;
SELECT
CASE #test_field1
-- List columns here that you might want to return:
WHEN 'last_name_display_status' THEN last_name_display_status
WHEN 'last_name_display_for_other_partcpnt' THEN last_name_display_for_other_partcpnt
WHEN 'create_date' THEN create_date
-- Return a value for an invalid name here:
ELSE NULL
END AS test_field1,
CASE #test_field2
-- List columns here that you might want to return:
WHEN 'last_name_display_status' THEN last_name_display_status
WHEN 'last_name_display_for_other_partcpnt' THEN last_name_display_for_other_partcpnt
WHEN 'create_date' THEN create_date
-- Return a value for an invalid name here:
ELSE NULL
END AS test_field2,
-- Rest of select unaffected by this change
amount_for_profile_visible
INTO
fn_field_name_1,
fn_field_name_2,
fn_amount_for_profile_visible
FROM member_account_settings
INNER JOIN tbl_members
ON member_account_settings.member_auto_id = tbl_members.member_id
WHERE
tbl_members.member_id = memb_id
;
And for the sake of completeness a copy of the first solution I proposed(the generated SQL):
-- Need to use #vars, since named vars aren't in scope for the generated SQL:
SET #output1 = '';
SET #output2 = '';
SET #output3 = '';
SET #input1 = memb_id;
-- We also need to store our generated SQL to a variable
SET #query = 'SELECT ' + #test_field1 + ',' + #test_field2 + ', amount_for_profile_visible INTO #output1, #output2, #output3 FROM member_account_settings INNER JOIN tbl_members ON member_account_settings.member_auto_id = tbl_members.member_id WHERE tbl_members.member_id = ?';
-- To execute the code we have to convert it to a prepared statement
-- named stmt here, because it's what most people use in this instance
PREPARE stmt FROM #query;
-- Execute the statement using our input variable
EXECUTE stmt USING #input1;
-- Delete the prepared statement now we've run it.
DEALLOCATE PREPARE stmt;
-- Store our #vars back into the named vars.
SET fn_field_name_1 = #output1;
SET fn_field_name_2 = #output2;
SET fn_amount_for_profile_visible = #output3;

EXECUTE PREPARE STATEMENT MySQL NOT WORKING

I've been trying to determine what's the problem with the stored procedure that I made in MySQL. I've had no problems in creating it but it's not working when I am trying to call it. The error that the Workbench is displaying is
Error Code: 1064. You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'SELECT ApplicantID, LastName, FirstName, Mid' at
line 4.
And here is my stored procedure,
-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`pinpoint_kevin`#`%` PROCEDURE `usp_Processing_GetApplicantByJobPostIDandStatus`(
IN _ApplicationStatus VARCHAR(100),
IN _JobPostID VARCHAR(64),
IN _startRowIndex INT,
IN _maximumRows INT,
IN _Order NVARCHAR(20))
BEGIN
DECLARE _OuterSelectString VARCHAR(1000);
DECLARE _OuterFromString1 VARCHAR(1000);
DECLARE _OuterFromString2 VARCHAR(1000);
DECLARE _InnerSelectString VARCHAR(2000);
DECLARE _InnerFromString VARCHAR(1000);
DECLARE _InnerWhereString VARCHAR(1000);
DECLARE _InnerOrderByString VARCHAR(1000);
DECLARE _OuterWhereString VARCHAR(1000);
DECLARE _ProcessingStepID VARCHAR(64);
DECLARE _ApplicationProcessingID VARCHAR(64);
DECLARE _YEHEY TEXT;
SELECT
ProcessingStepID
INTO
_ProcessingStepID
FROM
ProcessingStep
WHERE
ProcessingStepName = _ApplicationStatus;
SELECT
ApplicationProcessingID
INTO
_ApplicationProcessingID
FROM
ApplicationProcessing AS AP
INNER JOIN
ProcessingStep AS PS ON AP.ProcessingStepID = PS.ProcessingStepID
WHERE
PS.ProcessingStepName = _ApplicationStatus
ORDER BY
AP.TransactionDate
LIMIT
1;
SET
_OuterSelectString = '
SET
#row_num = 0;
SELECT
ApplicantID,
LastName,
FirstName,
MiddleName,
Email,
ContactNumber,
ApplicantCount,
ApplicationNumber,
ResumeStatus,
LastTransactionDate,
MovedBy,
StepType,
AdministeredBy,
Evaluation,
Recommendation,
DateTaken,
Mark,
RowRank
';
SET
_OuterFromString1 = 'FROM (
';
SET
_InnerSelectString = 'SELECT
(SELECT
COUNT(*)
FROM
Applicant_2 AS App
INNER JOIN
ApplicantJobPost AS AJP ON App.ApplicantID = AJP.ApplicantID
INNER JOIN
ApplicationStatus AS APPS ON AJP.ApplicationStatusID = APPS.ApplicationStatusID
WHERE
APPS.ApplicationStatusName = ?
AND
AJP.JobPostId = ? AND AJP.IsForwarded = 0) AS ApplicantCount,
App.ApplicantID AS ApplicantID,
App.LastName AS LastName,
App.FirstName AS FirstName,
App.MiddleName AS MiddleName,
App.Email AS Email,
App.BirthDate AS BirthDate,
App.Address AS Address,
App.ContactNumber AS ContactNumber,
App.FileName AS FileName,
App.FileExtension AS FileExtension,
App.DateCreated AS DateCreated,
AJP.ApplicationNumber AS ApplicationNumber,
AJP.IsReadResume AS ResumeStatus,
AP.TransactionDate AS LastTransactionDate,
AP.MovedBy AS MovedBy,
AP.ProcessingStepType AS StepType,
AP.AdministeredBy AS AdministeredBy,
AP.Evaluation AS Evaluation,
AP.Recommendation AS Recommendation,
AP.DateTaken AS DateTaken,
AJP.Mark AS Mark,
#row_num := #row_num + 1 AS RowRank
';
SET
_InnerFromString = 'FROM
Applicant_2 AS App
INNER JOIN
ApplicantJobPost AS AJP ON App.ApplicantID = AJP.ApplicantID
INNER JOIN
ApplicationStatus AS APPS ON AJP.ApplicationStatusID = APPS.ApplicationStatusID
INNER JOIN
ApplicationProcessing AS AP ON AP.ApplicantJobPostID = AJP.ApplicantJobPostID
';
SET
_InnerWhereString = 'WHERE
APPS.ApplicationStatusName = ?
AND
AJP.JobPostId = ?
AND
AP.ProcessingStepID = ?
AND
AJP.IsForwarded = 0
';
IF (_ApplicationStatus = 'Exam' OR _ApplicationStatus = 'Interview')
THEN
SET _InnerWhereString = 'WHERE
APPS.ApplicationStatusName = ?
AND
AJP.JobPostId = ?
AND
AP.ProcessingStepID = ?
AND
AJP.IsForwarded = 0
AND
AP.ApplicationProcessingID = ? ';
END IF;
SET
_OuterFromString2 = ') AS WithRowNumbers
';
SET
_OuterWhereString = 'WHERE
RowRank > _startRowIndex AND RowRank <= (_startRowIndex + _maximumRows)
';
IF (_Order = 'Transaction')
THEN
SET
_InnerOrderByString = 'ORDER BY
AP.TransactionDate,
LastName,
IsReadResume,
Mark,
DateTaken DESC
';
ELSEIF (_Order = 'TransactionDesc')
THEN
SET
_InnerOrderByString = 'ORDER BY
AP.TransactionDate DESC,
LastName,
IsReadResume,
Mark,
DateTaken DESC
';
ELSEIF (_Order = 'Last NameDesc')
THEN
SET
_InnerOrderByString = 'ORDER BY
LastName DESC,
IsReadResume,
Mark,
AP.TransactionDate DESC,
DateTaken DESC
';
ELSEIF (_Order = 'Last Name')
THEN
SET
_InnerOrderByString = 'ORDER BY
LastName,
IsReadResume,
Mark,
AP.TransactionDate DESC,
DateTaken DESC
';
ELSEIF (_Order = 'Resume StatusDesc')
THEN
SET
_InnerOrderByString = 'ORDER BY
IsReadResume DESC,
Mark,
AP.TransactionDate DESC,
LastName,
DateTaken DESC
';
ELSEIF (_Order = 'Resume Status')
THEN
SET
_InnerOrderByString = 'ORDER BY
IsReadResume,
Mark,
AP.TransactionDate DESC,
LastName,
DateTaken DESC
';
END IF;
SET _YEHEY = CONCAT(_OuterSelectString, _OuterFromString1, _InnerSelectString, _InnerFromString, _InnerWhereString, _OuterFromString2, _OuterWhereString);
SET #WholeQuery = _YEHEY;
PREPARE statement FROM #WholeQuery;
SET #a = _ApplicationStatus;
SET #b = _JobPostID;
SET #c = _ApplicationStatus;
SET #d = _JobPostID;
SET #e = _ProcessingStepID;
IF (_ApplicationStatus = 'Exam' OR _ApplicationStatus = 'Interview')
THEN
SET #f = _ApplicationProcessingID;
EXECUTE statement USING #a, #b, #c, #d, #e, #f;
ELSE
EXECUTE statement USING #a, #b, #c, #d, #e;
END IF;
DEALLOCATE PREPARE statement;
SELECT _YEHEY;
SELECT #WholeQuery;
END
I've already tried copying the resulting string/query and run it in another window and replaced the appropriate values for the variables and it's working.
I'm stuck with this stored procedure. I hope you could help me. Thanks!
As documented under SQL Syntax for Prepared Statements:
SQL syntax for prepared statements does not support multi-statements (that is, multiple statements within a single string separated by “;” characters).