0

What is wrong with the syntax or query?

SET @q=1000;
SET @p=5.00;

SELECT @ccount := COUNT(*) FROM 1detail WHERE price>=@p;
if(@ccount='0') THEN 
INSERT INTO 1detail (price,quantity) VALUES (@p,@q); 

ELSE

INSERT INTO 2detail (price,quantity) VALUES (@p,@q);  
END IF;

It gives me the 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(@ccount='0') THEN INSERT INTO 1detail (price,quantity) VALUES (@p,@q)' at line 1:

To create table (that is working):

CREATE TABLE 1detail 
(
quantity int, 
price DECIMAL(15,2) 
);

CREATE TABLE 2detail 
(
quantity int, 
price DECIMAL(15,2) 
);


INSERT INTO 1detail
(quantity, price)
VALUES
('5', '10');
1
  • 1
    Is this code inside a function or procedure or trigger? Commented Jul 19, 2014 at 21:35

1 Answer 1

1

Table names that start with digits need to be escaped. And, if is only used inside functions, stored procedures, and triggers. Assuming this code is "if"-safe:

SET @q=1000;
SET @p=5.00;

SELECT @ccount := COUNT(*) FROM `1detail` WHERE price>=@p;
if(@ccount='0') THEN 
INSERT INTO `1detail`(price,quantity) VALUES (@p,@q); 
ELSE
INSERT INTO `2detail`(price,quantity) VALUES (@p,@q);  
END IF;

If not, you can just do this as two inserts:

INSERT INTO `2detail`(price,quantity)
    VALUES (@p, @q)
    WHERE exists (select 1 from `detail` where price >= @p)

INSERT INTO `1detail`(price,quantity)
    VALUES (@p, @q)
    WHERE not exists (select 1 from `detail` where price >= @p)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.