INSERT INTO if conditions are met - mysql

A user is only meant to have up to 3 keys registered to his account at any one time. To add a new key, the user must first delete another key to "make room" for a new one.
I want this to be checked server-side, but I can't get the query to work. Here is what I tried:
IF (SELECT COUNT(serial_key_nbr)
FROM keys_table WHERE user_id = 9) <= 2
THEN INSERT INTO keys_table (user_id, serial_key_nbr)
VALUES (9, 'abc123')
How to do this?

You can use the below mention Script for the same:
INSERT INTO keys_table (user_id, serial_key_nbr)
SELECT 9, 'abc123' FROM DUAL
WHERE
(SELECT COUNT(serial_key_nbr)
FROM keys_table WHERE user_id = 9)<=2

if you want to use an if to do a conditional select then I would put it in a variable like so.
BEGIN
DECLARE var1 INT;
SELECT COUNT(serial_key_nbr) INTO var1
FROM keys_table
WHERE user_id = 9;
IF var1 <= 2
THEN
INSERT INTO keys_table (user_id, serial_key_nbr)
VALUES (9, 'abc123')
END IF;

A trigger might be the way to go. If a condition is met, a trigger before inserting in the table can perform an invalid operation and cause the insert operation to fail:
delimiter $$
create trigger keep_three before insert on keys_table for each row
begin
if (select count(serial_key_nbr) from keys_table where user_id = new.user_id) >= 3 then
insert into non_existent_table (non_existent_field) values (new.user_id);
end if;
end$$
delimiter ;
Ugly, but it might work.
Reference:
"MySQL Triggers: How do you abort an INSERT, UPDATE or DELETE with a trigger?"
Another solution (better I think) is to forcibly delete an entry before attepting the insert. When there are less than 3 entries, the insert procedes normally:
delimiter $$
create trigger keep_three before insert on keys_table for each row
begin
while (select count(serial_key_nbr) from keys_table where user_id = new.user_id) >= 3 do
delete from keys_table where user_id = new.user_id
-- OPTIONAL: Add an ordering criteria to define which entry is deleted first
limit 1;
end while;
end$$
delimiter ;
I think this is cleaner.
A third way (I've found it here). It will return an error message (by signaling sqlstate 45000: Unhandled user defined exception) associated with the defined condition:
delimiter $$
create trigger keep_three before insert on keys table for each row
begin
declare msg varchar(255);
declare n int default 0;
set n = (select count(serial_key_nbr) from keys_table where user_id = new.user_id);
if n >= 3 then
set msg = "INSERT failed: There must be only three entries for each user. Delete an entry first";
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg;
end if;
end$$
delimiter ;
A cleaner version of my first option.

Related

Trigger to validate room capacity

I'm trying to do a room capacity validation for a specific date using a before trigger.
This is the current trigger I'm using:
delimiter $$
create trigger my_insert_trigger before insert on my_table
for each row
begin
if (select count(*) from my_table where room_type = new.room_type) > 3 then
signal sqlstate '45000';
end if;
end;
$$
delimiter ;
I currently have two columns in the same table which are date and room, this is my desired output
However this would not be the case because the trigger will still limit 'Single' three times regardless of date.
do a room capacity validation for a specific date
Just add the date to the control query:
delimiter $$
create trigger my_insert_trigger before insert on my_table
for each row
begin
if (
select count(*)
from my_table t
where t.room_type = new.room_type and t.date = new.date
) >= 3 then
signal sqlstate '45000';
end if;
end;
$$
delimiter ;
Note: because it has condition > 3, your existing code would allow 4 records per room. I changed that to >= 3 so only 3 records are allowed per room and date, which seems to be what you are looking for.

Error #1109 in MySql

This is my trigger.
I want to make trigger on 1 table (rezervare).
Trigger
DELIMITER //
CREATE TRIGGER verificare_nr_locuri
BEFORE INSERT ON Rezervare
FOR EACH ROW
BEGIN
IF ( SELECT Masa.NrLocuri FROM Rezervare, Masa
WHERE Masa.NumarMasa = Rezervare.NumarMasa ) < Rezervare.NumarPersoane THEN
SET NEW.NumarMasa = NULL;
END IF;
END //
DELIMITER ;
INSERT INTO Rezervare VALUES (123,106,2,'2016-12-11','2016-12-24',5);
INSERT INTO Rezervare VALUES (124,106,2,'2016-12-11','2016-12-24',4);
When I execute the trigger, it has been created. But, when I insert data into table rezervare, It become
#1109 - Unknown table 'rezervare' in field list.
How can I resolve this?
Table
I think you might need to use a JOIN for your SELECT clause.
BEGIN
IF (SELECT Masa.NrLocuri, Rezervare.NumarMasa FROM Masa JOIN Rezervare
WHERE Masa.NumarMasa = Rezervare.NumarMasa) < Rezervare.NumarPersoane THEN
SET NEW.NumarMasa = NULL;
END IF;

MySQL stored procedure insert multiple rows from list

How can I write a MySQL stored procedure to insert values from a variable sized list? More specifically I need to insert data into one parent table, get the ID from the insert, and then insert a variable number of child records along with the new ID into another table in a one-to-many relationship. My schema looks something like this:
TableA:
table_a_id -- Auto Increment
counter
some_data...
TableB:
table_b_id -- Auto Increment
table_a_id -- Foreign Key Constraint
some_data_from_list...
My stored procedure so far looks like this:
DELIMITER ;;
CREATE PROCEDURE insert_group_alert(
IN _some_data_a VARCHAR(255),
IN _data_list_b TEXT,
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
END;
START TRANSACTION;
INSERT INTO TableA (
some_data,
counter
)
VALUES (
_some_data_a,
1
)
ON DUPLICATE KEY UPDATE
counter = counter + 1;
SELECT last_insert_id()
INTO #newId;
LIST INSERT ???:
INSERT INTO TableB (
table_a_id, some_data
) VALUES (
#newId,
list_item,
);
END LIST INSERT ???
COMMIT;
END ;;
DELIMITER ;
My thought was to pass in a list of items to insert into table B via a comma delimited string. The values are strings. I am not sure what to do in the LIST INSERT section. Do I need a loop of some sort? Is this stored procedure I have so far the correct way to do this? I don't want to do a batch as I could potentially have hundreds or even thousands of items in the list. Is there a better solution? I am using straight JDBC.
Yes, you need a loop, in which you can use substring_index() to get the values within the list. The solution is based on the answers from this SO topic:
DELIMITER ;;
CREATE PROCEDURE insert_group_alert(
IN _some_data_a VARCHAR(255),
IN _data_list_b TEXT,
)
BEGIN
DECLARE strLen INT DEFAULT 0;
DECLARE SubStrLen INT DEFAULT 0;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
END;
START TRANSACTION;
INSERT INTO TableA (
some_data,
counter
)
VALUES (
_some_data_a,
1
) -- you do not really need this, since you do not provide an id
ON DUPLICATE KEY UPDATE
counter = counter + 1;
SELECT last_insert_id()
INTO #newId;
do_this:
LOOP
SET strLen = CHAR_LENGTH(_data_list_b);
INSERT INTO TableB (table_a_id, some_data) VALUES(#newId,SUBSTRING_INDEX(_data_list_b, ',', 1));
SET SubStrLen = CHAR_LENGTH(SUBSTRING_INDEX(_data_list_b, ',', 1))+2;
SET _data_list_b = MID(_data_list_b, SubStrLen, strLen); --cut the 1st list item out
IF _data_list_b = '' THEN
LEAVE do_this;
END IF;
END LOOP do_this;
COMMIT;
END ;;
DELIMITER ;

how can multiple values be inserted in a table skipping few values in mysql

I can enforce data restriction at the time of data insertion in a table using a trigger like following:
create table com(id int);
DELIMITER ;;
CREATE TRIGGER checkage_bi BEFORE INSERT ON com FOR EACH ROW
BEGIN
DECLARE dummy,baddata INT;
SET baddata = 0;
IF NEW.id > 20 THEN
SET baddata = 1;
END IF;
IF NEW.id < 1 THEN
SET baddata = 1;
END IF;
IF baddata = 1 THEN
SELECT CONCAT('Cannot Insert This Because id ',NEW.id,' is Invalid')
INTO dummy FROM information_schema.tables;
END IF;
END;;
this will restrict the values which will not meet the restriction condition.
But the problem is that if I insert multiple values along then for some values which do not meet the condition the other values will also be restricted from entry to table.
What I want is that when I insert multiple values along then the values that do not meet the condition should be skipped and the rest get inserted into the table
i.e. no any error is given.
Only the the bad values will be skipped and the other values will be inserted that's it.
Please give me some idea to do so.Thanks in advance...
You should better use stored Procedures rather than triggers for this purpose because you are not permitted within a stored function or trigger to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger itself.
DELIMITER ;;
create table com(id int,var char(40));;
create procedure Validate(IN id int,IN var char(40))
BEGIN
declare entry_id int;
SET entry_id=id;
IF (id > 20) OR (id < 1) THEN
SET entry_id=NULL;
END IF;
insert into com values(entry_id,var);
END;;
Here is the output screen

Trigger not working as expected

I trying execute an trigger on mysql database.
The command executes successfully, but the trigger not working.
DELIMITER #
CREATE TRIGGER generate_coupon AFTER INSERT ON order
FOR EACH ROW
BEGIN
DECLARE userid, couponvalue INT;
DECLARE couponcode VARCHAR;
SELECT idUser INTO userid FROM indication WHERE email = NEW.email;
SET couponvalue = 20;
SET couponcode = 'abc123';
INSERT INTO coupon(idUser,idOrder,couponvalue,couponcode) values(userid, NEW.id, couponvalue, couponcode);
END#
DELIMITER ;
I suspect your problem arises from the collisions between your variables couponvalue and couponcode with the same-named columns in your coupon table. As documented under Local Variable Scope and Resolution:
A local variable should not have the same name as a table column.
You could simplify your trigger to the following and, in so doing, avoid this problem entirely:
CREATE TRIGGER generate_coupon AFTER INSERT ON order FOR EACH ROW
INSERT INTO coupon
(idUser, idOrder, couponvalue, couponcode)
SELECT idUser, NEW.id, 20, 'abc123'
FROM indication
WHERE email = NEW.email
;