techno
techno

Reputation: 6500

How to Check if a value exist in a Table,If it exists then Delete it?

I have a simple database named customer with a single table data.I want to check if a customer name exits in the database,if then i want to delete it.I'm using MYSQL Connector for this.

EDIT:
I want to make sure the value is present before deleting to display
a simple user message.

Upvotes: 0

Views: 1282

Answers (2)

vyegorov
vyegorov

Reputation: 22895

Why not just deleting it?

DELETE FROM customers WHERE customer_name = 'John Smith';

If it exists, it will be deleted. Otherwise no rows will be affected.

EDIT:

If you need a more complicated process, then I recommend (in order):

  1. creating ON DELETE FOR EACH ROW trigger, that will auto update flags upon deletion;
  2. developing a function/procedure for this purpose;
  3. performing a set of actions within a transaction block, like:
    START TRANSACTION;
    UPDATE flag_table SET is_deleted = 1 WHERE customer_name = 'John Smith';
    DELETE FROM customers WHERE customer_name = 'John Smith';
    COMMIT;

It would be easier to answer if you could provide more details on your design.

Upvotes: 6

Sudeep Mukherjee
Sudeep Mukherjee

Reputation: 71

you can use a trigger for this purpose, mysql will delete if any repetation is found on insertion.

Upvotes: 0

Related Questions