MARIADB : Insert and Update table based on data from another table - mysql

/* Here is the code i used to merge but i get error and am unable update
Error : SQL Error [1064][42000] You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the righr syntax to use near 'Merge temp2 as t' at line 1
*/
BEGIN
MERGE temp2 as t
using temp1 as s ON (t.slno = s.slno)
-- Insert values when data no present
WHEN NOT MATCHED THEN INSERT VALUES
(s.slno,s.name,s.address);
-- Update when values present
WHEN MATCHED then UPDATE SET
t.slno = s.slno,
t.name = s.name,
t.address = s.address;
END

You could probably use this:
INSERT INTO temp2 (slno, name, address) SELECT slno, name, address FROM temp1
ON DUPLICATE KEY UPDATE
slno = VALUES(slno), name = VALUES(name), address = VALUES(address)

Related

Creating a trigger to add new row to another table after new record using if statement

I cannot seem to get this trigger to work. I keep getting this 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 '' at line 6
SELECT * FROM website_queries;
CREATE DEFINER=`name`
TRIGGER `add_subscribed_users`
AFTER INSERT ON `website_queries` FOR EACH ROW
BEGIN
IF NEW.subscribed = 0 THEN
INSERT INTO users SET id=DEFAULT, firstName = NEW.firstName, lastName = NEW.lastName, mobile=DEFAULT, email = NEW.email, admin=DEFAULT, createdAt = NEW.createdAt, subscribed = NEW.subscribed;
END IF;
END; //
I am using 10.5.15-MariaDB-cll-lve doing this through phpMyAdmin
You do not need in IF.
CREATE DEFINER=`name` TRIGGER `add_subscribed_users`
AFTER INSERT ON `website_queries`
FOR EACH ROW
INSERT INTO users (firstName, lastName, email, createdAt, subscribed)
SELECT NEW.firstName, NEW.lastName, NEW.email, NEW.createdAt, NEW.subscribed
WHERE NEW.subscribed = 0;
In this single-statement form you do not need in BEGIN-END and DELIMITER too.

MySQL 8 Transaction resulting in error for using multiple sql statements

I have 3 tables, one is named SKU_Data, and 2 are named Fabric_Code and Product_Type respectively.
SKU_Data has 2 foreign key columns, one stores id of Fabric_Code and the other stores id of Product_Type.
I wrote an SQL transaction to put data into SKU_Data. (Using MySQL 8)
START TRANSACTION;
SELECT id INTO #fabricId FROM Fabric_Codes WHERE Fabric_Code = 'SOME_CODE';
SELECT id INTO #productTypeId FROM Product_Types WHERE Product_Type = 'SOME_TYPE';
INSERT INTO SKU_Data (Item_Sku_Code, Date_Introduced, Fabric_Id, Product_Type_Id, CP)
VALUES ('SOME_STRING_ID', '2012-04-03 14:00:45', #fabricId, #productTypeId, 41);
IF (ERROR) THEN
ROLLBACK;
ELSE
COMMIT;
END IF;
Now I am getting below mentioned error:
SQL Error [1064] [42000]: 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 'SELECT id INTO #fabricId FROM Fabric_Codes WHERE Fabric_Code = 'VELVETS';
SELEC' at line 3
Error position: line: 2
This error too vague to solve, any idea how to go about fixing this?
When I run the query SELECT id INTO #fabricId FROM Fabric_Codes WHERE Fabric_Code = 'VELVETS'; alone it works fine.
I tried changing the delimiter that also didn't work.
Do not use intermediate variables. Execute your action in single INSERT .. SELECT (which is a transaction itself):
INSERT INTO SKU_Data (Item_Sku_Code, Date_Introduced, Fabric_Id, Product_Type_Id, CP)
SELECT 'SOME_STRING_ID',
'2012-04-03 14:00:45',
Fabric_Codes.id,
Product_Types.id,
41
FROM Fabric_Codes
CROSS JOIN Product_Types
WHERE Fabric_Codes.Fabric_Code = 'SOME_CODE'
AND Product_Types.Product_Type = 'SOME_TYPE';

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

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

select if and update issue

Am using this sql to do an update on duplicate key
IF (SELECT COUNT(*) FROM `mlm_settings` WHERE `key` = 'notify_type' AND `user_id`=7 >0 )
UPDATE mlm_settings SET value='2' WHERE user_id = 7
ELSE
BEGIN
INSERT INTO `mlm_settings` (`key`, `value`,`user_id`) VALUES ('notify_type', '2',7)
END
by i get an sql error in mysql saying
#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 'IF (SELECT COUNT(*) FROM
`mlm_settings` WHERE `key` = 'notify_type' AND `user_id' at line 1
i can't figure what is the cause of the error, as the names of the tables are valid and the values are of the same data type
what could be the error?
You can only use IF statements in stored procedures, not normal queries.
If there's a unique index on (key, user_id) in the table, you can use:
INSERT INTO mlm_settings (`key`, value, user_id) VALUES ('notify_type', '2', 7)
ON DUPLICATE KEY UPDATE value = '2';
IF control block cannot be used OUTSIDE of functions. Try this:-
SELECT IF( EXISTS(
SELECT COUNT(*) FROM `mlm_settings` WHERE `key` = 'notify_type' AND `user_id`=7 >0), 1, 0)