MYSQL query error - mysql

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');

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)

Related

Within a stored-procedure the value of a field returned from a select query cannot recognized

Im mySQL I have the following stored procedure. Inside the sp I have a select query and then the dt value is being used in the if clause.
CREATE DEFINER=`cefcy`#`localhost` PROCEDURE `insert_checkup`(IN `p_id` INT(11), IN `u_id`INT(11), IN `v_id` INT(11) )
NO SQL
BEGIN
SELECT max(id) as ver_id, max(dt) as dt FROM ps_versioning as ps_v where ps_v.patient_id= p_id and ps_v.user_id = u_id;
IF (DATE(dt)=CURDATE()) THEN
INSERT INTO `endorse_checkup` (`patient_id`, `checkup_date`, `status`, `version_id`) VALUES (p_id, CURRENT_TIMESTAMP() , 1, v_id );
END IF;
END
However, when I'm trying to call it, I get the message: Error Code: 1054 Unknown column 'dt' in 'field list'
If edit your procedure "as is", then
CREATE
DEFINER=`cefcy`#`localhost`
PROCEDURE `insert_checkup`(IN `p_id` INT(11), IN `u_id`INT(11), IN `v_id` INT(11) )
NO SQL
BEGIN
SELECT MAX(id), MAX(dt) INTO #ver_id, #dt
FROM ps_versioning as ps_v
WHERE ps_v.patient_id= p_id
AND ps_v.user_id = u_id;
IF (DATE(#dt)=CURDATE()) THEN
INSERT INTO `endorse_checkup` (`patient_id`, `checkup_date`, `status`, `version_id`)
VALUES (p_id, CURRENT_TIMESTAMP() , 1, v_id );
END IF;
END
But it is unclear what's the aim to select MAX(id) which is not used later...

Increment a number field via a trigger INSERT in MySQL

I'm building a data versioning system, and I need to increment a version number each time a new row is added to the version table, but it increments once and then stops:
DELIMITER |
CREATE TRIGGER trigger2 AFTER UPDATE ON something
FOR EACH ROW
BEGIN
IF NEW.updated_at <> OLD.updated_at THEN
INSERT INTO versions_something (
`id`,
`some_id`,
`version`,
`title`,
`description`,
`created_at`,
`updated_at`
) VALUES (
null,
NEW.id,
1,
NEW.title,
NEW.description,
NOW(),
NOW()
);
END IF;
UPDATE
versions_something
SET
version = (SELECT MAX(version)) + 1
WHERE versions_something.id = LAST_INSERT_ID();
END;
|
DELIMITER ;
I've tried putting the UPDATE into a separate trigger (AFTER INSERT ON versions_something ...), but MySQL complains that it's clashing with the trigger before it.
I've tried the UPDATE on its own, using the last ID in the table and it works each time, so I have no idea what's happening.

Create a trigger to insert the old data to a new table

Here is the table I created.
USE my_guitar_shop;
DROP TABLE IF EXISTS Products_Audit;
CREATE TABLE Products_Audit (
audit_id INT PRIMARY KEY,
category_id INT REFERENCES categories(category_id),
product_code VARCHAR ( 10 ) NOT NULL UNIQUE ,
product_name VARCHAR ( 255 ) NOT NULL,
list_price INT NOT NULL,
discount_percent INT NOT NULL DEFAULT 0.00 ,
date_updated DATETIME NULL);
Create a trigger named products_after_update. This trigger should insert the old data about the product into the Products_Audit table after the row is updated. Then, test this trigger with an appropriate UPDATE statement.
Here is the trigger I created but the data is not showing up in the Products_Audit table it is showing all null.
USE my_guitar_shop;
DROP TRIGGER IF EXISTS products_after_update;
DELIMITER $$
CREATE TRIGGER products_after_update
BEFORE UPDATE ON products
FOR EACH ROW
BEGIN
INSERT INTO products_audit (audit_id, product_id, category_id, product_code,
product_name, list_price, discount_percent, date_updated)
SELECT audit_id, products.product_id, products.category_id, products.product_code,
products.product_name,products.list_price, products.discount_percent, date_updated
FROM products JOIN products_audit
ON products_audit.audit_id = (SELECT audit_id FROM inserted);
END $$
DELIMITER ;
EDIT with the INSERT INTO
USE my_guitar_shop;
DROP TRIGGER IF EXISTS products_after_update;
DELIMITER $$
CREATE TRIGGER products_after_update
BEFORE UPDATE ON products
FOR EACH ROW
BEGIN
INSERT INTO products_audit (audit_id, product_id, category_id,product_code,
product_name, list_price, discount_percent, date_updated)
VALUES (OLD.audit_id, OLD.product_id, OLD.category_id, OLD.product_code,
OLD.product_name, OLD.list_price, OLD.discount_percent, OLD.date_updated)
DELIMITER ;
You are overcomplicating the insert. As mysql documentation on triggers says:
In an UPDATE trigger, you can use OLD.col_name to refer to the columns
of a row before it is updated and NEW.col_name to refer to the columns
of the row after it is updated.
Therfore, use the OLD.column_name format in the insert. Also, I would set the audit_id field to auto increment and leave it out of the insert:
INSERT INTO products_audit (product_id, category_id, product_code,
product_name, list_price, discount_percent, date_updated)
VALUES (OLD.product_id, OLD.category_id, OLD.product_code,
OLD.product_name, OLD.list_price, OLD.discount_percent, OLD.date_updated)
Here's an example of how I do it:
CREATE OR REPLACE EDITIONABLE TRIGGER E_TABLE_TRG
before insert or update or delete on e_table
for each row
declare
l_seq number;
begin
-- Get a unique sequence value to use as the primary key
select s_seq.nextval
into l_seq
from dual;
if inserting then
:new.date_opened := sysdate;
:new.last_txn_date := null;
:new.status := 'A';
end if;
if inserting then
insert into e_table_history
(
t_seq,
user_id,
date_opened,
last_txn_date,
status,
insert_update_delete,
insert_update_delete_date
)
values
(
l_seq,
:new.user_id,
:new.date_opened,
:new.last_txn_date,
:new.status,
'I',
sysdate
);
elsif updating then
insert into e_table_history
(
t_seq,
date_opened,
last_txn_date,
status,
insert_update_delete,
insert_update_delete_date
)
values
(
l_seq,
:new.date_opened,
:new.last_txn_date,
:new.status,
'U',
sysdate
);
else
insert into e_table_history
(
t_seq,
date_opened,
last_txn_date,
status,
insert_update_delete,
insert_update_delete_date
)
values
(
l_seq,
:old.date_opened,
:old.last_txn_date,
:old.status,
'D',
sysdate
);
end if;
end;
/
ALTER TRIGGER E_TABLE_TRG ENABLE;
/

MySQL: Insert with conditional

I must perform the following situation down, but when you run got the error:
SQL Error (1064): 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 'INTO produto_seriais(serial_id) VALUES( SELECT id
FROM seriais WHERE serial =' at line 5
SELECT CASE WHEN (
SELECT COUNT(id) FROM seriais WHERE serial = '2020'
) > 1
THEN
(INSERT INTO produto_seriais(serial_id) VALUES(
SELECT id FROM seriais WHERE serial = '2020'
))
ELSE (
INSERT INTO seriais (serial) VALUE('2020');
SET #last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO produto_seriais (serial_id) VALUES (#last_id_in_table1);
)
END;
The case is as follows:
I'll get in "serial" table by serial "X". If it already exists, unless your ID in the "produto_seriais" table. If there is (serial), I will save the same, recover your ID and save to "produto_seriais". Any suggestions for how to do this?
Important Note: This routine will run will be thousands of times each execution (10,000 or more, depending on the quantity of serial).
P.s.: Sorry for my bad english.
Try a stored procedure
DELIMITER //
CREATE PROCEDURE sp_produto_seriais(IN `p_serial_id`)
IF EXISTS (SELECT * FROM seriais WHERE serial = p_serial_id )
BEGIN
INSERT INTO produto_seriais (serial_id)
SELECT id
FROM seriais
WHERE serial = p_serial_id
END
ELSE
BEGIN
INSERT INTO seriais (serial) VALUE(p_serial_id);
INSERT INTO produto_seriais (serial_id) VALUES (LAST_INSERT_ID());
END //
DELIMITER ;
usage:
CALL sp_produto_seriais('2020')
You could use the if exists..else statement.
If exists (select * from ....)
Begin
Insert into ... Select id from table
End
Else
Begin
Insert..
End
Please fill .... with your statements. You could use the link here to convert it for MySQL.
Convert if exists for MySQL

Mysql sql error #1064

check the manual that corresponds to your MySQL server version for the right syntax to use near: 'SELECT count(*) FROM capacity
WHERE
server=NEW.server
AND
feed' at line 2
my code:
DROP TRIGGER IF EXISTS newsmonitoringrawdata.TNTInsertionTrigger;
CREATE TRIGGER TgtInsertionTrigger BEFORE INSERT ON tnews
FOR EACH ROW BEGIN
SET #isRecordCreated =
SELECT count(*) FROM capacity
WHERE
server=NEW.server
AND
feed=NEW.Feed
AND
date_Format(streamdt,'%Y-%m-%d %H:%i')=date_Format(NEW.StreamDT,'%Y-%m-%d %H:%i');
IF #isRecordCreated>0 THEN
UPDATE capacity
SET MsgNumber=MsgNumber+1,
size=size+NEW.MSize
WHERE
server=NEW.server
AND
feed=NEW.feed
and
date_Format(streamdt,'%Y-%m-%d %H:%i')=date_Format(NEW.StreamDT,'%Y-%m-%d %H:%i');
ELSE
INSERT INTO capacity(server, feed, streamdt, msgNumber, size)
VALUES
(
NEW.server,
NEW.feed,
date_Format(NEW.StreamDT,'%Y-%m-%d %H:%i:00'),
1,
NEW.size
);
END IF;
END
SET #isRecordCreated = (
SELECT count(*) FROM capacity
WHERE
server=NEW.server
AND
feed=NEW.Feed
AND
date_Format(streamdt,'%Y-%m-%d %H:%i')=date_Format(NEW.StreamDT,'%Y-%m-%d %H:%i')
);
You have to add parantheses () around the query.