MySQL: Insert with conditional - mysql

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

Related

How do I use IF THEN ELSE to SELECT and INSERT or UPDATE Queries?

I've been trying to use the following query
IF EXISTS (SELECT id FROM users WHERE id = 1)
THEN
(INSERT INTO users (id, username) VALUES (2, user2))
ELSE
(UPDATE users SET username = 'userUpdated')
But I keep getting
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO users (id) VALUES (2)) ELSE (UPDATE users SET id = 11)' at line 1 */
Also tried using the following query
IF EXISTS (SELECT id FROM users WHERE id = 1)
THEN
(SELECT username FROM users WHERE id = 1)
ELSE
(INSERT INTO users (id, username) VALUES (1, 'user'))
But this time I got
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ELSE
(INSERT INTO users (id, username) VALUES (1, 'user'))' at line 4 */
Am I doing or understood something wrong?
The if statement can only be used in programming blocks, such as stored procedures, functions, and triggers.
In any case, MySQL offers simpler syntax for this functionality: insert . . . on duplicate key update.
To use it, id must have a unique index, unique constraint, or be defined as the primary key. Let me assume that a column so-named is already so-defined.
Then:
INSERT INTO users (id, username)
VALUES (2, user2)
ON DUPLICATE KEY UPDATE username = 'userUpdated';
Are you missing the END IF (and semi colons)?
IF EXISTS (SELECT id FROM users WHERE id = 1)
THEN
(SELECT username FROM users WHERE id = 1);
ELSE
(INSERT INTO users (id, username) VALUES (1, 'user'));
END IF;
Try This.
IF EXISTS (SELECT id FROM users WHERE id = 1)
begin
INSERT INTO users (id, username) VALUES (2, 'user2')
end
ELSE
UPDATE users SET username = 'userUpdated'
In MariaDB 10.1 and newer, you can use compound statements outside of stored procedures. This blog post gives a good description of what you can do with it.
Here's an example the blog:
BEGIN NOT ATOMIC
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
stmt1;
....
stmtN;
COMMIT;
END

Django migration sql for conditional triggers

I want to create a trigger that only inserts into table when the condition is met.
I've tried using various combinations of IF/BEGIN/END and WHERE, but Django returns me an SQL syntax error each time.
Here, type_user_id refers to the person who triggers the like, and user_id refers to the person who receives the notification. It should only trigger when they are not the same person.
operations = [
migrations.RunSQL(
"DROP TRIGGER like_notification",
"""
CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
FOR EACH ROW
IF (select user_id from channel WHERE channel_id IN
(SELECT channel_id FROM article WHERE article_id = NEW.article_id)) <> NEW.user_id
BEGIN
INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id)
VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id,
(SELECT user_id from channel WHERE channel_id IN
(SELECT channel_id FROM article WHERE article_id = NEW.article_id)
)
)
END;
"""
)
]
>>>django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the right syntax
to use near 'BEGIN\n INSERT INTO notification (type, type_id, article_id, is_re' at line 5")
and
CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
FOR EACH ROW
BEGIN
DECLARE #user_same Boolean;
SELECT 1 into #user_same
FROM channel
WHERE channel_id IN (select channel_id FROM article where article_id = NEW.article_id)
AND user_id = NEW.user_id;
IF #user_same <> 1
THEN
INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id,)
VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id, (
SELECT user_id from channel WHERE channel_id IN (
SELECT channel_id FROM article WHERE article_id = NEW.article_id)
)
END IF;
END;
>>>You have an error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near '#user_same Boolean;\n SELECT 1 into #user_same\n FRO' at line 4"
and
CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
FOR EACH ROW
INSERT INTO notification (type, type_id, article_id, is_read, type_user_iduser_id)
VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id,
(
SELECT user_id from channel WHERE channel_id IN
(SELECT channel_id FROM article WHERE article_id = NEW.article_id)
)
WHERE NOT user_id = NEW.user_id;
>>>You have an error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'WHERE NOT user
I don't really understand why none of them work. Any help would be much appreciated!
#variables are not DECLARED.
Either:
DECLARE user_same BOOLEAN;
SELECT 1 INTO user_same WHERE ...
or
SELECT #user_same := 1 WHERE ...
Better yet, this avoids the need for the variable.
IF (EXISTS SELECT * FROM ...)
Also, don't use the construct IN ( SELECT ... ); it is usually better to use WHERE EXISTS ( SELECT * FROM ... ) or JOIN ... ON ....
(There may be more problems after fixing those.)
Another easy way to do this.
You should add any symbols between ; delimiters for the appropriate converting MySQL syntax to the raw SQL.
CREATE TRIGGER trigger_name BEFORE INSERT ON table
FOR EACH ROW
BEGIN
IF NEW.number <> 'anynumber' AND NEW.number <> 'anynumber'
THEN
SET NEW.number = 'anynumber'; --
END IF; --
END
This example works due to the dash symbols.

My sql error in creating temporaty table stored procedure

I have a stored procedure query and inserting value in temp table.. but shows error
delimiter //
create procedure AccountLedgerViewUnderSundryDebtorCreditorCash()
begin
create temporary table temp_kk(accountGroupID varchar(50),HierarchyLevel varchar(50));
insert into temp_kk(accountGroupID,HierarchyLevel)
select accountGroupId, 1 as HierarchyLevel from tbl_AccountGroup
where accountGroupId='27'or accountGroupId = '28'or
accountGroupId = '11';
create temporary table temp_kk2(accountGroupID varchar(50),HierarchyLevel varchar(50));
insert into temp_kk2(accountGroupID,HierarchyLevel)
select e.accountGroupId, G.HierarchyLevel + 1 AS HierarchyLevel
from tbl_AccountGroup as e, temp_kk G
where e.groupUnder=G.accountGroupId ;
create temporary table temp_kk3(accountGroupID varchar(50),HierarchyLevel varchar(50));
insert into temp_kk3(accountGroupID,HierarchyLevel)
select * from temp_kk union all temp_kk2 ;
SELECT
ledgerId AS 'Account Ledger Id',
accountLedgerName AS 'Account Ledger Name',
accountGroupId AS 'Account Group Id',
openingBalance AS 'Opening Balance',
debitOrCredit AS 'Credit Or Debit',
defaultOrNot AS 'Editable Or Not',
description AS 'Description'
FROM tbl_AccountLedger
where accountGroupId IN (select accountGroupId from temp_kk3);
end //
delimiter ;
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 'temp_kk2 ; SELECT ledgerId AS [Account Ledger Id], acccountLedgerName' at line 20
This line:
select * from temp_kk union all temp_kk2 ;
Needs to be:
select * from temp_kk union all select * from temp_kk2 ;
At least, that what sticks out most obviously.
Though, I tend to avoid using select *. If you change the temp table, it will break. It also ends up making the code harder to read if you don't know for sure what all columns are in the table you're selecting from. Yes, it saves you some typing right now, but you'll lose that time-savings later on when you have to keep looking back at the table definition to figure out what exactly you're selecting.
Though, with these simple temp tables, it isn't as big of a deal.

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.

Use MySql function variables as table name in the query

I need to have a function that increments the certain ID in a table (like auto_increment)
I have smth like this
DELIMITER $$
DROP FUNCTION IF EXISTS `GetNextID`$$
CREATE FUNCTION `GetNextID`(tblName TEXT, increment INT)
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE NextID INT;
SELECT MAX(concat(tblName, 'ID')) + increment INTO NextID FROM concat('table_', tblName);
## SELECT MAX(articleID) + increment INTO NextID FROM table_article;
RETURN NextID;
END$$
DELIMITER ;
INSERT INTO `table_article` ( articleID, articleAlias ) VALUES ( GetNextID('article', 5), 'TEST' );
So i pass two variables: tblName (without table_ prefix), and the increment number. The commented line - SELECT query inside the function itself - works well, but i want to dynamically pass table name to the function and so get data from a certain col of certain table. What am I doing wrong?
The error is:
#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 '('table_', tblName);
RETURN NextID;
END' at line 6
if i simply try to select max value in such a way
SELECT MAX(articleID) + increment INTO NextID FROM tblName;
The error reports that tblName does not exist. How can i tell MySql that this is actually a var passed to the function, not an exact table name? If it is possible.
you need something like
prepare stmp from concat('SELECT MAX(ID) + ', increment, ' INTO NextID FROM table_', tblName);
execute stmp;
deallocate prepare stmp;