0

I want to solve an error. While i am exicuting this query i met with an error.

IF EXISTS (SELECT * FROM category_info WHERE category_name = 'Electronics')
BEGIN
select * from category_info;
END
ELSE 
BEGIN
     insert into category_info(category_name) values('Electronics');
END

Error:

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 'IF EXISTS (SELECT * FROM category_info WHERE category_name = 'Electronics') BEG' at line 1

I need help,Thanks in advance

jarlh
  • 35,821
  • 8
  • 33
  • 49

1 Answers1

0

It can be solved by using procedure.

delimiter $$
CREATE PROCEDURE Check_exists(IN categoryName  varchar(20))
BEGIN
IF EXISTS(SELECT * FROM category_info WHERE category_name = categoryName)
THEN 
    SELECT 'Already Exists' as status;
ELSE 
    INSERT INTO category_info(category_name) VALUES(categoryName); 
END IF;
END $$

and this procedure can be called by

call Check_Exists('Electronics');

It will display message "Already exists " if it is exists or else it will insert a row.