Can we execute IF ELSE without the procedure in mysql - mysql

Please find my code and provide me any alternate way to execute this code without procedure.
delimiter $$
create procedure dm()
begin
IF EXISTS (select * from sainikpuri_purchases where barcode = 12012271314) THEN
update sainikpuri_purchases set quantity = quantity+2 where barcode = 12012271314;update purchases set quantity = quantity-2 where barcode = 12012271314;
ELSE
INSERT INTO sainikpuri_purchases(id, vendor_name, quantity, from_location, location, cost, cost_of_price,invoice_number,serial_number,sarees_category,paid_gst,profit_percentage,sales_price,tag,barcode,discount,created_at,updated_at,status) SELECT id, vendor_name, 2, 'KPM', 'SNP', cost, cost_of_price,invoice_number,serial_number,sarees_category,paid_gst,profit_percentage,sales_price,tag,barcode,discount,created_at,updated_at,status FROM purchases where barcode = '12012271314';update sainikpuri_purchases set updated_at = current_timestamp where barcode = '12012271314';update purchases set quantity = quantity-2 where barcode = '12012271314';
END IF;
end $$
delimiter ; call dm();```

Related

SQL can I create an if statement if subquery returns more than 1 row?

Hi I'm making a procedure "AddToCart" I want to check if there is row with the same column values and if there is update it, if not insert a new row. I keep getting subquery returns more than 1 row.
CREATE PROCEDURE AddToCart(thisCustomerID INT, thisOrdersID INT, thisShoeID INT, thisQuantity INT)
BEGIN
DECLARE any_rows_found int;
IF (thisOrdersID IS NULL)
THEN
INSERT INTO orders (Date, CustomerID)
VALUES (CURRENT_DATE, thisCustomerID);
SELECT COUNT(*)
INTO any_rows_found
FROM Shoe_Orders
WHERE OrdersID = thisOrdersID
AND ShoeID = thisShoeID;
IF (any_rows_found > 0)
THEN
UPDATE shoe_orders
SET Quantity = Quantity + thisQuantity
WHERE ShoeID = thisShoeID
AND OrdersID = thisOrdersID;
ELSE
INSERT INTO shoe_orders (ShoeID, OrdersID, Quantity)
VALUES (thisShoeID, (SELECT ID
FROM orders
WHERE CustomerID = thisCustomerID
AND Date = CURRENT_DATE), thisQuantity);
END IF;
END IF;
END //

LAST INSERT ID SQL Subquery returns more than one row

I have the below Stored Procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS spCashDonation$$
CREATE PROCEDURE spCashDonation(IN fname varchar(50),IN lname varchar(50),IN telNo bigint, IN pmode tinyint,IN amt decimal(8,2), OUT rno varchar(20))
BEGIN
Set #rmain := (select trim(concat('DNB', DATE_FORMAT(CURRENT_DATE(), '%y'), DATE_FORMAT(CURRENT_DATE(), '%m'))));
IF ((trim(DATE_FORMAT(CURRENT_DATE(),'%m')) = 01) OR (trim(DATE_FORMAT(CURRENT_DATE(),'%m')) = 1)) THEN
Set #rpart = 1;
END IF;
IF ((trim(DATE_FORMAT(CURRENT_DATE(),'%m')) != 01) OR (trim(DATE_FORMAT(CURRENT_DATE(),'%m')) != 1)) THEN
Set #rpart := (select coalesce(max(ReceiptPart),0) from Donation) + 1;
END IF;
INSERT INTO Donation (ReceiptMain, ReceiptPart, firstName, lastName, telNo, payMode, Amount) VALUES (#rmain, #rpart, fname, lname, telNo, pmode, amt);
Set #lid := (select LAST_INSERT_ID()from donation);
select concat(ReceiptMain,ReceiptPart) into rno from donation where id = #lid;
END$$
DELIMITER ;
Call spCashDonation ('RAJIV','IYER',7506033048,0,1000,#rno);
select #rno;
When the table has no record, the first insert goes through fine. The upon the second insert it throws an error as
Error Code: 1242. Subquery returns more than 1 row
When I query for the last insert id, I get more than 1 value. So, I modified the last part of the procedure to:
Set #lid := (select max(LAST_INSERT_ID()) from donation);
Please advice, if this is fine as it should not hinder any concurrent inserts and future CRUD operations. Thanks in advance.
Set #lid := (select LAST_INSERT_ID() from donation);
In the above line remove the FROM statement. If more than one record in the Donation table it will return the same number of times the LAST_INSERT_ID() value.
So simply use Set #lid := (SELECT LAST_INSERT_ID()); it will work in your case.

MySQL Trigger - Where am I going wrong

Can someone tell me where I'm going wrong in creating this trigger in MySQL? Every time I try to create it, it keeps telling me there is an error.
USE `cl11-onestock`;
DELIMITER //
CREATE TRIGGER audit_insert
AFTER INSERT
ON stock_usage FOR EACH ROW
BEGIN
SET uUid = (SELECT UUID());
SET stockUsageId = (SELECT NEW.stock_usage_id);
SET siteId = (SELECT NEW.site_id);
SET date = (SELECT NEW.date);
SET patientName = (SELECT NEW.patient_name);
SET dentistDiscountId = (SELECT NEW.dentist_discount_id);
SET itemId = (SELECT NEW.item_id);
SET quantity = (SELECT NEW.quantity);
SET priceIncDiscount = (SELECT NEW.price_inc_discount);
SET vat = (SELECT NEW.vat);
SET priceIncVat = (SELECT NEW.price_inc_vat);
SET createdAt = (SELECT NEW.created_at);
SET updatedAt = (SELECT NEW.updated_at);
INSERT INTO stock_audit VALUES
(uUid, stockUsageId, siteId, date, patientName, dentistDiscountId, itemId, quantity, priceIncDiscount, vat, priceIncVat, createdAt, updatedAt);
END; //
DELIMITER ;
You need to use the keyword new to access the field values after insert and not like you are doing with select and you can use directly inside the insert query
So the trigger should be as
DELIMITER //
CREATE TRIGGER audit_insert
AFTER INSERT
ON stock_usage FOR EACH ROW
BEGIN
INSERT INTO stock_audit VALUES
(new.UUID, NEW.stock_usage_id, NEW.site_id, NEW.date, NEW.patient_name, NEW.dentist_discount_id, NEW.item_id, NEW.quantity, NEW.price_inc_discount, NEW.vat, NEW.price_inc_vat, NEW.created_at, NEW.updated_at);
END; //
DELIMITER ;

How come this codes error? SQL Error code 1109: Unknown table 'o' in field list

When i run this code, it gives me error. From this code, there's several task to do:
(1) update tble customer by setting the address to '90 TYT' if c_id= 1
(2) view order_no,status,c_id,item_total remarks.
(3) if item_total 0, then update table order_status by setting remarks = 'UNAVAILABLE', else select order_no,status,item_total,remarks where status = 'waiting'.
Please help me fix the error. I'm new to SQL.
#drop procedure if exists usp_GetAnything;
delimiter //
create procedure usp_GetAnything()
begin
select c_id,lname,address,city
from customer;
update customer
set address = '90 TYT'
where c_id = 1;
select o.order_no,o.o_status,c.c_id,o.item_total,o.remarks
from customer c, order_status o
where c.c_id=o.c_id;
if (o.item_total > 0) then
update order_status o
set remarks = 'UNAVAILABLE'
where order_no > '123';
else
select order_no,o_status,item_total,remarks
from order_status
where o_status = 'waiting';
end if;
end
It's failing on the line:
if (o.item_total > 0)
o is unidentified outside of the previous select clause including all the selected variables.
In order to use the results that returned from the previous select you should select ... INTO...
(select the result arguments into declared local variables).
You can find here the following example:
DELIMITER //
CREATE PROCEDURE `proc_WHILE` (IN param1 INT)
BEGIN
DECLARE variable1, variable2 INT;
SET variable1 = 0;
WHILE variable1 < param1 DO
INSERT INTO table1 VALUES (param1);
SELECT COUNT(*) INTO variable2 FROM table1;
SET variable1 = variable1 + 1;
END WHILE;
END //
You can see that variable1 and variable2 are declared in the beginning of the procedure and later on used with select ... INTO ....

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;