Procedure delete from different table - mysql

I am trying to create a procedure that will delete everything related to the cust_id. When I enter the cust_id when I execute the procedure it deletes everything from the customer and invoice tables but not from the line table and I don't know why. This is what I have
BEGIN
DELETE FROM CUSTOMER WHERE CUS_CODE = cust_id;
DELETE FROM INVOICE WHERE INVOICE.CUS_CODE = cust_id;
DELETE FROM LINE WHERE EXISTS (SELECT * FROM INVOICE WHERE
INVOICE.INV_NUMBER = LINE.INV_NUMBER AND invoice.CUS_CODE = cust_id);
END

If you delete all records related to a customer from the invoices table first, then the exists() operator cannot return true for any of the records in the line table.
The easiest solution is to reverse the order of the deletion and delete from the line table first.
A slightly better solution is to use a multi-table delete syntax a delete the matching records from all 3 tables with a single statement:
delete invoice, customer, line
from customer
left join invoice on customer.cus_code=invoice.cus_code
left join line on invoice.inv_number=line.inv_number
where customer.cus_code=cust_id
But, the best would be to use foreign keys with the on delete cascade option set and do not use stored proc at all.
However, in most countries you are not allowed to delete invoices just like that, so you should really check your business requirements before implementing such deletion operation.

Related

Insert records from multiple tables into one table using any loop statement on mysql

I have four tables [tbl1], [tbl2], [tbl3], [tbl4]. The first three tables have records of their own, from which a selected few is to be inserted into the fourth table i.e [tbl4]. I'm expected to use a stored procedure whose parameter specifies the number of records to be inserted into [tbl4]. For example:
CALL storedproc(4);
will insert 4 records into tbl4 according to the inner join statement and seeing their common id's.
But mysql keeps giving error: "Duplicate entry 'some_name' for key 'PRIMARY' ".
BEGIN
DECLARE nums int(50);
SET nums=0;
INSERT INTO tblstudteach (SELECT tblstudent.id, tblstudent.Namess, tblgrades.Mark, tblgraderange.Score, tblteacher.teachername FROM tblstudent INNER JOIN tblgrades ON tblstudent.id=tblgrades.stdid
INNER JOIN tblgraderange ON tblgrades.Mark BETWEEN tblgraderange.StartingGrade
AND tblgraderange.EndingGrade INNER JOIN tblteacher ON tblstudent.id=tblteacher.studid)
LIMIT num;
SET nums=nums+1;
END
I also have no clue as how I could include a loop statement that can loop through each record and insert into [tbl4].

How update table with duplicate primary key?

I trying to update a table with another table of other database, I the last updated I created a function to save more than one category in one product, so, I when a run the old script to update my table, a constraint error appears. I understand the situation and why that is happenning, but how I allow the update with the table with duplicates data? Is there a way to disable the constraint?
My query
UPDATE novourbano.oc_product_to_category oc
INNER JOIN erp_product_category erp ON oc.product_id = erp.erp_productid
SET oc.product_id = erp.erp_productid,
oc.category_id = erp.erp_categoryid
WHERE oc.product_id <> 0
I try to use that:
SET GLOBAL FOREIGN_KEY_CHECKS=0;
But still not working. Any suggestion? Thank's in advance!
If the table name reflects the table purpose the primary key should be
PRIMARY KEY(product_id, category_id)
in order to avoid duplicates like several rows with the same product_id and category_id.
You can use IGNORE for this update:
UPDATE IGNORE novourbano.oc_product_to_category oc
INNER JOIN erp_product_category erp ON oc.product_id = erp.erp_productid
SET oc.product_id = erp.erp_productid,
oc.category_id = erp.erp_categoryid

Mysql Insert if the Specific Column is not available for the same Employee

I have a controller to save a record
My Table contains BELOW Fields
This is Must (It has to repeat in LOOP).
I want to insert a record single time in a table for a Employee Id, and it should not repeat again. But Same Employee can have multiple Batch Ids and Multiple Course ID's.
If I take Unique as a Employee Id that is not working again to insert the another record to the same employee.
This process should repeat inside the loop and I need to get the Last Inserted ID from the Table and have to assign the number of students in the another table. This everything is working fine if I create a Procedure in Mysql and If I call Procedure. But my Linux server is not executing and throwing MySQL error.
Here is my query and
<code>
$insert_staff_assign = "insert into staff_assign
(`main_course_id`, `main_batch_id`, `section`, `semester_course_id`, `emp_mas_staff_id`, `emp_category`)
VALUES
(:main_course_id, :main_batch_id, :section_id, :semester_course_id, :emp_mas_staff_id, :emp_category)
ON DUPLICATE KEY UPDATE
main_course_id=:main_course_id, main_batch_id=:main_batch_id, section=:section_id, semester_course_id=:semester_course_id, emp_mas_staff_id=:emp_mas_staff_id, emp_category=:emp_category ";
insert into staff_assign
(`main_course_id`, `main_batch_id`, `section`, `semester_course_id`, `emp_mas_staff_id`, `emp_category`)
VALUES
(:main_course_id, :main_batch_id, :section_id, :semester_course_id, :emp_mas_staff_id, :emp_category)
ON DUPLICATE KEY UPDATE
main_course_id=:main_course_id, main_batch_id=:main_batch_id, section=:section_id, semester_course_id=:semester_course_id, emp_mas_staff_id=:emp_mas_staff_id, emp_category=:emp_category
insert into staff_assign
(`main_course_id`, `main_batch_id`, `section`, `semester_course_id`, `emp_mas_staff_id`, `emp_category`)
SELECT * FROM (
SELECT
:main_course_id, :main_batch_id, :section_id, :semester_course_id, :emp_mas_staff_id, :emp_category
) AS tmp WHERE NOT IN (
SELECT emp_mas_staff_id FROM staff_assign WHERE emp_mas_staff_id = $save_emp_mas_staff_id
) LIMIT 1
</code>
Please send me the query to get rid of this problem.
The above are my queries.
I found the answer for the above question.
mysql.proc problem.
In my mysql my mysql.proc was corrupted. That is the reason it doesn't execute the above query.
To fix the above issue you need to update mysql in linux.

update if exit and add new mysql ..

i got the following mysql query..I have tried many different format but cant seem to get this to work.
I got two tables. table mic.temp has three columns while table products has quite a few.
I need to update values into table products from table mic.temp. The matching column is model number.
i have written the following query but it updates all the field.I only need to update the values found in temp table and also auto increment the product table.if a value is not found then insert it.I don't mind if non existent values in temp table are entered as null.
mysql_query('INSERT INTO products(products_id, products_quantity, products_model, products_ean, products_image, products_price, products_date_added, products_last_modified, products_date_available, products_weight, products_status, products_tax_class_id, manufacturers_id, products_ordered, products_last_import, icecat_prodid, vendors_id, products_availability)
SELECT model, stock, price
FROM mic_temp
ON DUPLICATE KEY UPDATE set
products.products_quantity = mic_temp.stock,
products.products_price= mic_temp.price');
Check this:
Update products join mic_temp on products.modelnumber=mic_temp.modelnumber set
products.product_quantity=mic_temp.stock, products.product_price=mic_temp.price;
Specify all columns of mic_temp which you want to insert or update in products table under
set statement.

MySql stored procedures, delete record logically or phisically depending on existing table references

I have to write a Stored Procedure to delete record from a table.
I have a memory table "tableids" where I store all the ids to delete from another table, say "addresses".
CREATE TABLE `tempids` (
`id` INT(11) NULL DEFAULT NULL
)
COLLATE='latin1_swedish_ci'
ENGINE=MEMORY
ROW_FORMAT=DEFAULT
I could do this:
DELETE FROM addresses INNER JOIN tempids ON addresses.id = tempids.id;
BUT I want to physically delete the records in the addresses table if they have no references in other known tables in my model; otherwise I want to delete the records logically. I'd like to do this in a single shot, that is without writing a loop in my SP.
In pseudo-sql code:
DELETE
FROM addresses
WHERE
id NOT IN (SELECT address_id FROM othertable1 WHERE address_id=(SELECT id FROM tempids))
AND id NOT IN (SELECT address_id FROM othertable2 WHERE address_id=(SELECT id FROM tempids))
...more possible references in other tables
IF "no records deleted"
DELETE FROM addresses INNER JOIN tempids ON addresses.id = tempids.id;
ELSE
UPDATE addresses SET deleted=TRUE INNER JOIN tempids ON addresses.id = tempids.id;
How do I accomplish this?
Thanks.
You can check ROW_COUNT() function value after deleting.
http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_row-count
So "no records deleted" condition is replaced with ROW_COUNT() == 0