MySQL Stored Procedures issue with if then else statements - mysql

I have the need to store the changes in our invoice system to export it to the account system (which is a 3rd party app).
What I'm trying to do is to add two triggers.
ON INSERT : A new invoice is added, it has to be marked as new in another table, so in the next migration, generate the appropiate ASCII to import it in the accounting system.
ON UPDATE: This is a bit more complicated, this can happen when an invoice is modified or when an invoice becomes payed / or it was marked to be payed and finally it hasnt.
Both Triggers call the same procedure.
DROP PROCEDURE IF EXISTS `marca_factura_modificada`;
DELIMITER |
CREATE PROCEDURE `marca_factura_modificada`( IN nempresa_in int, IN nfactura_in int, IN cany_in char(2), IN cobrada boolean )
BEGIN
DECLARE existeix_factura INT;
DECLARE abans_afegir_factura INT;
DECLARE abans_afegir_cobrament INT;
SELECT NFactura,afegir_factura,afegir_cobrament
INTO existeix_factura,abans_afegir_factura,abans_afegir_cobrament
FROM factures_modificades
WHERE NEmpresa = nempresa_in
AND NFactura = nfactura_in
AND CAny = cany_in
LIMIT 1;
IF existeix_factura IS NULL THEN
IF new.DataFactura = CURDATE() THEN
IF (new.LComptat = 1 OR new.LCreditCobrat = 1) THEN
INSERT INTO factures_modificades (NEmpresa, NFactura, CAny,afegir_factura,afegir_cobrament )
VALUES (nempresa_in, nfactura_in, cany_in,1,1);
ELSE
INSERT INTO factures_modificades (NEmpresa, NFactura, CAny,afegir_factura,afegir_cobrament )
VALUES (nempresa_in, nfactura_in, cany_in,1,0);
END IF
ELSE
/* Si no és d'avui i no hi ha registre es que ja es va afegir la factura en el seu dia */
INSERT INTO factures_modificades (NEmpresa, NFactura, CAny,afegir_factura,afegir_cobrament )
VALUES (nempresa_in, nfactura_in, cany_in,0,1);
END IF
ELSE
IF(cobrada = 0 AND abans_afegir_factura = 0) THEN
DELETE FROM factures_modificades WHERE NEmpresa = nempresa_in AND NFactura = nfactura_in AND CAny = cany_in LIMIT 1;
ELSEIF (cobrada = 1 AND abans_afegir_cobrament = 0) THEN
UPDATE factures_modificades SET afegir_cobrament = 1 WHERE NEmpresa = nempresa_in AND NFactura = nfactura_in AND CAny = cany_in;
ELSEIF (cobrada = 0 AND abans_afegir_cobrament = 1) THEN
UPDATE factures_modificades SET afegir_cobrament = 0 WHERE NEmpresa = nempresa_in AND NFactura = nfactura_in AND CAny = cany_in;
END IF
END IF
END
|
DELIMITER ;
But this doesnt work on mysql 5.5 (I think there is some issue in IF THEN ELSE code, but I dont see where.

Solved!
Now it works. The problem was END IF wants a ; in the end.
DROP PROCEDURE IF EXISTS `marca_factura_modificada`;
DELIMITER |
CREATE PROCEDURE `marca_factura_modificada`( IN nempresa_in int, IN nfactura_in int, IN cany_in char(2), IN cobrada boolean,IN DataFactura date )
BEGIN
DECLARE existeix_factura INT;
DECLARE abans_afegir_factura INT;
DECLARE abans_afegir_cobrament INT;
SELECT NFactura,afegir_factura,afegir_cobrament
INTO existeix_factura,abans_afegir_factura,abans_afegir_cobrament
FROM factures_modificades
WHERE NEmpresa = nempresa_in
AND NFactura = nfactura_in
AND CAny = cany_in
LIMIT 1;
IF (existeix_factura) IS NULL THEN
IF (DataFactura = CURDATE()) THEN
IF (cobrada) THEN INSERT INTO factures_modificades (NEmpresa, NFactura, CAny,afegir_factura,afegir_cobrament ) VALUES (nempresa_in, nfactura_in, cany_in,1,1);
ELSE INSERT INTO factures_modificades (NEmpresa, NFactura, CAny,afegir_factura,afegir_cobrament ) VALUES (nempresa_in, nfactura_in, cany_in,1,0);
END IF;
ELSE INSERT INTO factures_modificades (NEmpresa, NFactura, CAny,afegir_factura,afegir_cobrament ) VALUES (nempresa_in, nfactura_in, cany_in,0,1);
END IF;
ELSE
IF(cobrada = 0 AND abans_afegir_factura = 0) THEN DELETE FROM factures_modificades WHERE NEmpresa = nempresa_in AND NFactura = nfactura_in AND CAny = cany_in LIMIT 1;
ELSEIF (cobrada = 1 AND abans_afegir_cobrament = 0) THEN UPDATE factures_modificades SET afegir_cobrament = 1 WHERE NEmpresa = nempresa_in AND NFactura = nfactura_in AND CAny = cany_in;
ELSEIF (cobrada = 0 AND abans_afegir_cobrament = 1) THEN UPDATE factures_modificades SET afegir_cobrament = 0 WHERE NEmpresa = nempresa_in AND NFactura = nfactura_in AND CAny = cany_in;
END IF;
END IF;
END
|
DELIMITER ;

Related

MYSQL TRIGGER with DECLARE value

I want to set value using declare on trigger. The trigger is as follow:
CREATE DEFINER=`root`#`localhost` TRIGGER `update_queue_after_insert` AFTER INSERT ON `encounter_note` FOR EACH ROW DECLARE is_exist INT;
SET is_exist = ( SELECT count(*) FROM practice_last_updated_module WHERE practice_id = NEW.practice_id );
IF NEW.enc_source = 'OP' THEN
UPDATE practice_queue_list PQL SET
PQL.vital_check = IF (NEW.vs_weight <> 0 OR NEW.vs_height <> 0 OR NEW. vs_temperature <> 0 OR LENGTH(NEW.vs_blood_pressure) > 0 <> NEW.vs_pulse <> 0 OR NEW.vs_respiration <> 0, 1, 0)
WHERE PQL.encounter_id = NEW.id AND PQL.practice_place_id = NEW.practice_id;
END IF;
IF is_exist > 0 THEN
UPDATE practice_last_updated_module SET encounter = UNIX_TIMESTAMP(NOW()) where practice_id = NEW.practice_id;
ELSE:
INSERT INTO practice_last_updated_module (practice_id, encounter) VALUES (NEW.practice_id, UNIX_TIMESTAMP(NOW()));
END IF;"
But it returns error on saving
The following query has failed: "CREATE DEFINER=root#localhost
TRIGGER update_queue_after_insert AFTER INSERT ON encounter_note
FOR EACH ROW DECLARE is_exist INT; SET is_exist = ( SELECT count(*)
FROM practice_last_updated_module WHERE
What's wrong with the statement?
Use 13.6.1 BEGIN ... END Compound-Statement Syntax.
Try (maybe you need to use DELIMITER):
DELIMITER //
CREATE TRIGGER `update_queue_after_insert` AFTER INSERT ON `encounter_note`
FOR EACH ROW
BEGIN -- <- BEGIN
DECLARE is_exist INT;
SET is_exist = ( SELECT count(*) FROM practice_last_updated_module WHERE practice_id = NEW.practice_id );
IF NEW.enc_source = 'OP' THEN
UPDATE practice_queue_list PQL
SET PQL.vital_check = IF (NEW.vs_weight <> 0 OR NEW.vs_height <> 0 OR NEW.vs_temperature <> 0 OR LENGTH(NEW.vs_blood_pressure) > 0 <> NEW.vs_pulse <> 0 OR NEW.vs_respiration <> 0, 1, 0)
WHERE PQL.encounter_id = NEW.id AND PQL.practice_place_id = NEW.practice_id;
END IF;
IF is_exist > 0 THEN
UPDATE practice_last_updated_module SET encounter = UNIX_TIMESTAMP(NOW()) where practice_id = NEW.practice_id;
-- ELSE:
ELSE
INSERT INTO practice_last_updated_module (practice_id, encounter) VALUES (NEW.practice_id, UNIX_TIMESTAMP(NOW()));
END IF;
END// -- <- END
DELIMITER ;

MySQL: Procedure Loops, but only inserts once

CREATE DEFINER=`root`#`localhost` PROCEDURE `GenerateCharges2`()
BEGIN
Declare sumFunding LONG;
Declare done INT DEFAULT FALSE;
Declare invoiceCharge LONG;
Declare agencyID INT;
declare invoiceID int;
Declare fundingID INT;
Declare amountOfFunding LONG;
Declare getInvoiceData CURSOR For select invoices.idInvoices, invoices.idAgencies, invoices.InvoiceAmount, fundings.FundingBalance, fundings.idfundings from invoices
inner join agencies on invoices.idAgencies = agencies.idAgencies
inner join fundings on agencies.idAgencies = fundings.IdAgencies
where processed =0
group by invoices.idInvoices;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
open getInvoicedata;
ze_loop: Loop
Fetch getInvoiceData into invoiceID, agencyID, invoiceCharge, amountOfFunding, fundingID;
if done then leave ze_loop;
end if;
if amountOfFunding > invoiceCharge then
insert into charges VALUES (invoiceCharge, invoiceID, fundingID);
end if;
end loop;
close getInvoiceData;
END
My issue is that if you were to insert a select statement, it runs a proper amont of times. However, the insert statement only inserts once with sample data. In every case, amnountOfFunding is ALWAYS greater than invoiceCharge. Desired results is to have all inserts happen for rows fetched.
I have this loop and insert every record that i need! Maybe you can modifiy or update yours loop with that!
DECLARE done INT DEFAULT FALSE ;
DECLARE l_local_formato_retail_codigo,
l_producto_sku,
l_producto_descripcion_sra,
l_producto_marca,
l_producto_categoria VARCHAR (100) ;
DECLARE l_precio DECIMAL (20, 7) DEFAULT 0 ;
DECLARE l_un_1 INT (20) DEFAULT 0 ;
DECLARE l_un_2 INT (20) DEFAULT 0 ;
DECLARE l_clp_1 DECIMAL (20, 7) DEFAULT 0 ;
DECLARE l_clp_2 DECIMAL (20, 7) DEFAULT 0 ;
DECLARE contador INT DEFAULT 0 ;
DECLARE valores CURSOR FOR
SELECT
local_formato_retail_codigo,
producto_sku,
producto_descripcion_sra,
producto_marca,
producto_categoria
FROM
base_comercial
WHERE mes_fecha = fecha
GROUP BY producto_sku,
local_formato_retail_codigo
ORDER BY local_formato_retail_codigo ASC,
producto_sku ASC ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE ;
TRUNCATE precio_cd ;
OPEN valores ;
read_loop :
LOOP
FETCH valores INTO l_local_formato_retail_codigo,
l_producto_sku,
l_producto_descripcion_sra,
l_producto_marca,
l_producto_categoria ;
IF done
THEN LEAVE read_loop ;
END IF ;
SET l_clp_1 =
(SELECT
ROUND(SUM(sellout_clp), 7)
FROM
base_comercial
WHERE anno = DATE_FORMAT(fecha, '%Y')
AND mes = DATE_FORMAT(fecha, '%c')
AND local_formato_retail_codigo = l_local_formato_retail_codigo
AND producto_sku = l_producto_sku) ;
SET l_clp_2 =
(SELECT
ROUND(SUM(sellout_clp), 7)
FROM
base_comercial
WHERE anno = DATE_FORMAT(
DATE_ADD(fecha, INTERVAL - 1 MONTH),
'%Y'
)
AND mes = DATE_FORMAT(
DATE_ADD(fecha, INTERVAL - 1 MONTH),
'%c'
)
AND local_formato_retail_codigo = l_local_formato_retail_codigo
AND producto_sku = l_producto_sku) ;
SET l_un_1 =
(SELECT
SUM(sellout_un)
FROM
base_comercial
WHERE anno = DATE_FORMAT(fecha, '%Y')
AND mes = DATE_FORMAT(fecha, '%c')
AND local_formato_retail_codigo = l_local_formato_retail_codigo
AND producto_sku = l_producto_sku) ;
SET l_un_2 =
(SELECT
SUM(sellout_un)
FROM
base_comercial
WHERE anno = DATE_FORMAT(
DATE_ADD(fecha, INTERVAL - 1 MONTH),
'%Y'
)
AND mes = DATE_FORMAT(
DATE_ADD(fecha, INTERVAL - 1 MONTH),
'%c'
)
AND local_formato_retail_codigo = l_local_formato_retail_codigo
AND producto_sku = l_producto_sku) ;
IF (ISNULL(l_clp_1))
THEN SET l_clp_1 = 0 ;
END IF ;
IF (ISNULL(l_clp_2))
THEN SET l_clp_2 = 0 ;
END IF ;
IF (ISNULL(l_un_1))
THEN SET l_un_1 = 0 ;
END IF ;
IF (ISNULL(l_un_2))
THEN SET l_un_2 = 0 ;
END IF ;
SET l_precio = ((l_clp_1 + l_clp_2) / (l_un_1 + l_un_2)) ;
IF (ISNULL(l_precio))
THEN SET l_precio = 0 ;
END IF ;
INSERT INTO precio_cd
VALUES
(
l_local_formato_retail_codigo,
l_producto_sku,
l_producto_descripcion_sra,
l_producto_marca,
l_producto_categoria,
l_precio
) ;
END LOOP read_loop ;
CLOSE valores ;
SELECT
*
FROM
precio_cd ;

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '< '

I am trying to write a stored procedure for a MSSQL 2008 R2 database.
The stored procedure should compare some values and return a bit/bool value.
Depending on a parameter (#PlatformCode), the procedure should choose the right check.
But I get an error, in the lines where I try to store my result in the output var.
CREATE PROCEDURE CheckVersion
#PlatformCode nvarchar(4),
#ClientVersion int,
#ConfigId int = 1,
#Response bit OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #version int
IF #PlatformCode = 'a'
BEGIN
SET #version = (SELECT aVersion FROM AppConfigTable WHERE ConfigID = #ConfigId)
SET #Response = (#version <= #ClientVersion)
END
IF #PlatformCode = 'i'
BEGIN
SET #version = (SELECT iVersion FROM AppConfigTable WHERE ConfigID = #ConfigId)
SET #Response = (#version <= #ClientVersion)
END
END
GO
Is there maybe a better way, to return the result?
What you are missing is the CASE statement
CREATE PROCEDURE CheckVersion
#PlatformCode nvarchar(4),
#ClientVersion int,
#ConfigId int = 1,
#Response bit OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #version int
IF #PlatformCode = 'a'
BEGIN
SET #version = (SELECT aVersion FROM AppConfigTable WHERE ConfigID = #ConfigId)
SET #Response = CASE WHEN (#version <= #ClientVersion) THEN 1 ELSE 0 END
END
IF #PlatformCode = 'i'
BEGIN
SET #version = (SELECT iVersion FROM AppConfigTable WHERE ConfigID = #ConfigId)
SET #Response = CASE WHEN (#version <= #ClientVersion) THEN 1 ELSE 0 END
END
END
GO
better yet you can do it like this:
CREATE PROCEDURE CheckVersion
#PlatformCode nvarchar(4),
#ClientVersion int,
#ConfigId int = 1,
#Response bit OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF #PlatformCode = 'a'
BEGIN
SELECT #Response = CASE WHEN aVersion <= #ClientVersion THEN 1 ELSE 0 END FROM AppConfigTable WHERE ConfigID = #ConfigId
END
IF #PlatformCode = 'i'
BEGIN
SELECT #Response = CASE WHEN iVersion <= #ClientVersion THEN 1 ELSE 0 END FROM AppConfigTable WHERE ConfigID = #ConfigId
END
END
GO

Getting Error ''Incorrect arguments to EXECUTE'' while executing procedure in mysql

I am Getting Error
''Incorrect arguments to EXECUTE''
while executing procedure in mysql
My parameters are
CALL appclient.P_GetClientList( 1, 10, 1, ' AND -1!=0 AND isActive = 1', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, 0,#V_TotalPages,#V_TotalRecords,#V_TabCountDetails);
DELIMITER $$
DROP PROCEDURE IF EXISTS `appclient.P_GetClientList`$$
CREATE PROCEDURE `appclient.P_GetClientList`(
IN V_ReportId INT,
IN V_PagePerRecordN INT,
IN V_PageN INT,
IN V_Condition VARCHAR (4000),
IN V_SortColIndex VARCHAR (10),
IN V_SortOrder VARCHAR (10),
IN V_Param1 VARCHAR (500),
IN V_Param2 VARCHAR (500),
IN V_Param3 VARCHAR (500),
IN V_Param4 VARCHAR (500),
IN V_Param5 VARCHAR (500),
IN V_Param6 VARCHAR (500),
IN V_Param7 VARCHAR (500),
IN V_Param8 VARCHAR (500),
IN V_Param9 VARCHAR (500),
IN V_Param10 VARCHAR (500),
IN V_IsPdf INT,
OUT V_TotalPages INT,
OUT V_TotalRecords INT,
OUT V_TabCountDetails VARCHAR (500)
)
BEGIN
DECLARE V_Query VARCHAR (4000) ;
DECLARE V_OrderBy NVARCHAR (500) ;
DECLARE V_ClientListId SMALLINT ;
DECLARE V_Logo NVARCHAR (50) ;
DECLARE V_Status VARCHAR (10) ;
DECLARE V_ClientId SMALLINT ;
DECLARE V_IsManDocsReq BIT ;
DECLARE V_IsApproveLink BIT ;
DECLARE V_ThemeId BIT ;
DECLARE V_IsActive BIT ;
DECLARE V_IsThemeLogoUploded BIT ;
DECLARE V_IsRegDocsUploaded BIT ;
DECLARE V_IsOnlinePayment BIT ;
DECLARE V_IsConfigurationDone BIT ;
DECLARE V_IsClientBidTermConfigured BIT ;
DECLARE V_IsClientBidTermGridLink BIT ;
DECLARE V_IsClientBidTermCreateLink BIT ;
DECLARE V_IsCPPPRequired TINYINT ;
DECLARE V_CPPPClientCount TINYINT ;
DECLARE V_State BOOLEAN DEFAULT FALSE;
IF(V_SortColIndex != '' AND V_SortColIndex IS NOT NULL AND V_SortOrder != '' AND V_SortOrder IS NOT NULL) THEN
SELECT V_OrderBy = CONCAT(RSCD.selectFieldName, ' ', V_SortOrder)
FROM `appreport.Tbl_ReportSearchColumnDetail` RSCD
WHERE RSCD.reportId = V_ReportId AND RSCD.columnId = V_SortColIndex;
END IF;
SET #V_Query = CONCAT('SELECT COUNT(1) into #V_TotalRecords FROM `appclient.tbl_Client` CM INNER JOIN `appclient.tbl_Department` DM ON CM.deptId = DM.deptId
WHERE 1 = 1 ',V_Condition);
SELECT #V_Query;
SELECT #V_TotalRecords;
PREPARE stm FROM #V_Query;
EXECUTE stm USING #V_TotalRecords;
DEALLOCATE PREPARE stm;
SET #V_Query1 = CONCAT('SELECT A.clientId, A.domainName, A.deptName, A.isManDocsReq, A.themeId, A.logo, A.isOnlinePayment,0 AS isApproveLink, 0 AS isClientBidTermCreateLink, 0 AS isClientBidTermGridLink, '''' AS cstatus, A.isActive,A.isCPPPRequired,A.cppCount
FROM (SELECT #row_number:=#row_number+1 AS row_number, CM.clientId, CM.domainName, DM.deptName,CM.isManDocsReq, CM.themeId, CM.logo, CM.isOnlinePayment, CM.isActive,CM.isCPPPRequired,CPC.cppCount
FROM `appclient.tbl_Client` CM
INNER JOIN `appclient.tbl_Department` DM ON CM.deptId = DM.deptId
LEFT OUTER JOIN (SELECT clientId,COUNT(clientId) cppCount FROM `appclient.tbl_ClientCPPPConfig` GROUP BY clientId) CPC ON CPC.clientId = CM.clientId,(SELECT #row_number:=0) AS t
WHERE 1 = 1', V_Condition,') AS A
WHERE ',#row_number, ' BETWEEN ' ,CAST((#V_PageN - 1) * #V_PagePerRecordN + 1 AS CHAR) ,' AND ' ,CAST(#V_PageN * #V_PagePerRecordN AS CHAR)) ;
SELECT #V_Query1;
/*INSERT INTO `ttbl_ClientList` (
clientId,domainName,deptName,isManDocsReq,themeId,logo,isOnlinePayment,isApproveLink,isClientBidTermCreateLink,isClientBidTermGridLink,cstatus,
isActive,isCPPPRequired,cppCount
)
*/
PREPARE stm FROM #V_Query1 ;
EXECUTE stm;
DEALLOCATE PREPARE stm; --
Loop_lable: WHILE (#V_Query1) DO
SET V_IsApproveLink = 0;
SET V_IsThemeLogoUploded = 0;
SET V_IsConfigurationDone = 0;
SET V_IsRegDocsUploaded = 0;
SET V_IsClientBidTermConfigured = 0;
SET V_IsClientBidTermGridLink = 0;
SET V_IsClientBidTermCreateLink = 0;
SET V_ClientId = 0;
SET V_IsCPPPRequired = 0;
SET V_CPPPClientCount = 0;
SELECT V_ClientId = clientId, V_IsManDocsReq = isManDocsReq, V_ThemeId = themeId, V_Logo = logo,
V_IsOnlinePayment = isOnlinePayment, V_IsActive = isActive, V_IsCPPPRequired = isCPPPRequired
FROM ttbl_ClientList WHERE clientListId = V_ClientListId;
/*
IF (#ROWCOUNT = 0) THEN
LEAVE Loop_lable;
END IF;
*/
IF (V_ThemeId != '' AND V_Logo != '' AND V_Logo != 'abc') THEN /* Theme and Logo */
SET V_IsThemeLogoUploded = 1;
END IF;
IF ((SELECT COUNT(1)
FROM appclient.tbl_ClientEventType CET INNER JOIN appmaster.tbl_Field MF ON CET.eventTypeId = MF.eventTypeId AND MF.isActive = 1
WHERE CET.clientId = V_ClientId AND CET.isActive = 1)
= (SELECT COUNT(1) FROM appclient.tbl_CustomParameter CP
INNER JOIN appclient.tbl_ClientEventType CET ON CP.eventTypeId = CET.eventTypeId AND CP.clientId=CET.clientId AND CET.isActive=1
WHERE CP.clientId = V_ClientId)) THEN /* Default Configuration */
SET V_IsConfigurationDone = 1;
END IF;
IF (V_IsManDocsReq = 1) THEN /* Bidder Registration Docs Required */
IF EXISTS (SELECT 1 FROM appclient.tbl_ClientRegDoc WHERE clientId = V_ClientId AND isActive = 1) THEN /* Mandatory Registration Docs Defined */
SET V_IsRegDocsUploaded = 1;
END IF;
ELSE
SET V_IsRegDocsUploaded = 1;
END IF;
/* Client bid term required */
IF ((SELECT COUNT(1)
FROM `appclient.tbl_ClientEventType` CET
LEFT OUTER JOIN `appclient.tbl_ClientBidTerm` CBT ON CET.clientId = CBT.clientId AND CET.eventTypeId = CBT.eventTypeId AND CBT.isActive = 1
WHERE CET.clientId = V_ClientId AND CET.isActive = 1 AND CBT.clientBidTermId IS NULL) = 0) THEN
SET V_IsClientBidTermGridLink = 1;
END IF;
IF ((SELECT COUNT(1)
FROM `appclient.tbl_ClientEventType` CET INNER JOIN appclient.tbl_ClientLanguage CL ON CET.clientId = CL.clientId AND CL.isActive = 1
WHERE CET.clientId = V_ClientId AND CET.isActive = 1)
= (SELECT COUNT(1) FROM `appclient.tbl_ClientBidTerm` CBT WHERE CBT.clientId = V_ClientId AND CBT.isActive = 1)) THEN
SET V_IsClientBidTermConfigured = 1;
ELSE
SET V_IsClientBidTermCreateLink = 1;
END IF;
IF (V_IsThemeLogoUploded = 1 AND V_IsConfigurationDone = 1 AND V_IsRegDocsUploaded = 1 AND V_IsClientBidTermConfigured = 1) THEN
SET V_IsApproveLink = 1;
END IF;
IF (V_IsActive = 1) THEN
SET V_IsApproveLink = 0;
SET V_Status = 'Approved';
ELSE
SET V_Status = 'Pending';
END IF;
UPDATE `ttbl_ClientList`
SET isApproveLink = V_IsApproveLink, isClientBidTermCreateLink = V_IsClientBidTermCreateLink,
isClientBidTermGridLink = V_IsClientBidTermGridLink, isOnlinePayment = V_IsOnlinePayment,
cstatus = V_Status
WHERE clientListId = V_ClientListId;
SET V_ClientListId = V_ClientListId + 1;
END WHILE;
SELECT clientId AS FieldValue1, CONCAT( domainName ,' </A> <BR>', deptName) AS FieldValue2,
deptName AS FieldValue3, isManDocsReq AS FieldValue4,CASE WHEN isCPPPRequired = 0 THEN isApproveLink WHEN (isCPPPRequired = 1 AND cppCount = 1) THEN isApproveLink ELSE 0 END AS FieldValue5, cstatus AS FieldValue6,
isClientBidTermCreateLink AS FieldValue7, isClientBidTermGridLink AS FieldValue8, isOnlinePayment AS FieldValue9,
CASE WHEN (isCPPPRequired = 1) THEN 1 ELSE 0 END AS FieldValue11
FROM `ttbl_ClientList`;
SET V_TotalPages = CEILING( V_TotalRecords / V_PagePerRecordN);
SET V_TabCountDetails = '';
END$$
DELIMITER ;

mysql stored procedure error (1172, 'Result consisted of more than one row')

When trying to run the following stored procedure from django, I get an OperationError (1172, 'Result consisted of more than one row') Any idea what I might be doing wrong?
-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `UpdatePrices`(IN storeId int, IN bottleSize VARCHAR(50))
BEGIN
DECLARE amount DECIMAL(10,2); DECLARE isCustom INT DEFAULT 0;
DECLARE changeType VARCHAR(50) DEFAULT 'State'; DECLARE updateType INT DEFAULT 0;
IF bottleSize = '1000 Ml' THEN
SELECT S1000IncreaseChoices INTO changeType FROM store_store WHERE StoreID = storeId;
IF changeType = 'State' THEN
SELECT updateType = 0;
END IF;
IF changeType = 'Flat' THEN
SELECT S1000IncreaseAmount INTO amount FROM store_store WHERE StoreID = storeId;
SELECT updateType = 1;
END IF;
IF changeType = 'Percent' THEN
SELECT 1 - S1000IncreaseAmount/100 INTO amount FROM store_store WHERE StoreID = storeId;
SELECT updateType = 2;
END IF;
END IF;
IF updateType = 0 THEN
update store_storeliquor SL
inner join liquor_liquor LL
on liquorID_id = id
set StorePrice = ShelfPrice
where BottleSize = bottleSize
and storeID_id = storeId
and custom = 0;
END IF;
IF updateType = 1 THEN
update store_storeliquor SL
inner join liquor_liquor LL
on liquorID_id = id
set StorePrice = OffPremisePrice + amount
where BottleSize = bottleSize
and storeID_id = storeId
and custom = 0;
END IF;
IF updateType = 1 THEN
update store_storeliquor SL
inner join liquor_liquor LL
on liquorID_id = id
set StorePrice = OffPremisePrice / amount
where BottleSize = bottleSize
and storeID_id = storeId
and custom = 0;
END IF;
END
I'm not sure if it matters, but I initiate the stored procedure like so:
def priceupdate(request, store_id):
cursor = connection.cursor()
cursor.callproc("UpdatePrices", (store_id, '1000 ML'))
cursor.close()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Your SELECT...INTO queries give result sets with more then one record. The WHERE filters are incorrect - they compare two the same values StoreID = storeId. Rename IN storeId int parementer to another name. For example - IN storeId_param int
The query will be like this -
SELECT S1000IncreaseChoices INTO changeType FROM store_store WHERE StoreID = storeId_param;
This is a Bug and you need to apply something like that:
SELECT id,data INTO x,y FROM test.t1 LIMIT 1;