0

i'm trying to write a if exists else sql which will further use in c# winform with mysql, here is the test

IF NOT EXISTS(SELECT 1 from products where entity_id=1) select * from products;

i ran above sql in adminer but there is a error message, Syntax error near 'select * from products' at line 1

Anyone know what is the problem?

hkguile
  • 4,235
  • 17
  • 68
  • 139

2 Answers2

0

try this:

  DELIMITER $$

        DROP PROCEDURE IF EXISTS `verifyExist` $$
            CREATE PROCEDURE `verifyExist`()
            BEGIN
           IF NOT EXISTS(SELECT 1 from products where entity_id=1) THEN 
            select * from products;
          END IF;
    END$$

        DELIMITER ;
Danilo Bustos
  • 1,083
  • 1
  • 7
  • 9
0

First of all you should create a UNIQUE constraint on the columns.

ALTER TABLE products  ADD CONSTRAINT fk_products UNIQUE (column1, column2, etc..)

Then just insert the data:

INSERT INTO products (column1, column2, etc..) VALUES(value1, value2, etc..) ON DUPLICATE KEY UPDATE column1 = newValue, column2 = newValue2;
mrhallak
  • 1,138
  • 1
  • 12
  • 27