Using Select INTO Statement in Mysql Trigger based on If Condition - mysql

I want to write a trigger.
The trigger works in the following manner :
When table R_published gets a new entry, based on a column value in the entry(R_published.whichPublishable) it needs to copy a row from either the project_task_goodread_master table or the project_document_master table into the R_publishedGoodReads OR R_publishedDocuments tables respectively.
I have written the following trigger and I'm getting the error : "#1327 - Undeclared variable: R_publishedGoodReads"
CREATE TRIGGER trigger_after_published
AFTER INSERT ON R_published
FOR EACH ROW
BEGIN
IF (NEW.whichPublishable=1) THEN
SELECT * INTO R_publishedGoodReads FROM project_task_goodread_master
WHERE
goodReadID= new.publishedItemId;
ELSEIF (NEW.whichPublishable=2) THEN
SELECT * INTO R_publishedDocuments FROM project_document_master where
documentID=new.publishedItemId;
END IF
END
Is there anything wrong with the syntax ? Do I need to declare the table name that I am using for insert ? Thanks.

MySQL doesn't support SELECT...INTO TABLE. See MySQL Documentation

Try instead:
IF (NEW.whichPublishable=1) THEN
INSERT INTO R_publishedGoodReads (col1, col2...)
SELECT col1, col2... FROM project_task_goodread_master
WHERE goodReadID= new.publishedItemId;

Related

SELECT * INTO statement

I was trying to use this statement SELECT * INTO new_table FROM old_table but it's giving me the error of undeclared value. I wanted to create a back table from one existing table to another new table.
Do I have first to create another table? or am I missing something.
the link below shows that the same statement can be used, so I don't why it's not working for me
https://www.w3schools.com/sql/sql_select_into.asp
You should use the INSERT ... SELECT statement for MySQL instead.
INSERT INTO new_table
SELECT *
FROM old_table
But new_table must exist. If you have MySQL version >= 8.0.19, then you can use instead the following syntax:
INSERT INTO new_table TABLE old_table;
You may check 13.2.6.1 INSERT ... SELECT Statement.
Background information
The SELECT...INTO is not exactly standard, it has selective support by vendors.
The statement does exist in MySQL, but is used for "query result to be stored in variables or written to a file".

Create 'search' trigger before insert

I have the following sql syntax:
CREATE TRIGGER trigger_name
BEFORE INSERT
ON table FOR EACH ROW
BEGIN
END;
I need to check the table for values where field1='x' and field2='y'. If the values are found want the insertion to fail via php side. ($mysqli->error)
This can be done by attempting to select that value using mysql and count the results (num_rows). If the result returns 0, then you insert data into mysql table, as there is no data with the same value in your table.

SQL check if existing row, if not insert and return it

I'm having a problem with my sql query. I need to insert a data that needs to be checked first if it is existing or not. If the data is existing the sql query must return it, if not insert and return it. I already google it but the result is not quite suitable to my problem. I already read this.
Check if a row exists, otherwise insert
How to 'insert if not exists' in MySQL?
Here is a query that' I'm thinking.
INSERT INTO #tablename(#field, #conditional_field, #field, #conditional_field)
VALUES(
"value of field"
(SQL QUERY THAT CHECK IF THERE IS AN EXISTING DATA, IF NOT INSERT THE DATA and RETURN IT, IF YES return it),
"value of feild",
(SQL QUERY THAT CHECK IF THERE IS AN EXISTING DATA, IF NOT INSERT THE DATA and RETURN IT, IF YES return it)
);
Please take note that the conditional field is a required field so it can't be NULL.
Your tag set is quite weird, I'm unsure you require all the technologies listed but as long as Firebird is concerned there's UPDATE OR INSERT (link) construction.
The code could be like
UPDATE OR INSERT INTO aTable
VALUES (...)
MATCHING (ID, SomeColumn)
RETURNING ID, SomeColumn
Note that this will only work for PK match, no complex logic available. If that's not an option, you could use EXECUTE BLOCK which has all the power of stored procedures but is executed as usual query. And you'll get into concurrent update error if two clients execute updates at one time.
You could split it out into 2 steps
1. run a select statement to retrieve the rows that match your valus. select count (*) will give you the number of rows
2. If zero rows found, then run the insert to add the new values.
Alternatively, you could create a unique index form all your columns. If you try to insert a row where all the values exist, an error will be returned. You could then run a select statement to get the ID for this existing row. Otherwise, the insert will work.
You can check with if exists(select count(*) from #tablename) to see if there is data, but with insert into you need to insert data for all columns, so if there is only #field missing, you cant insert values with insert into, you will need to update the table and go with a little different method. And im not sure, why do you check every row? You know for every row what is missing? Are you comparing with some other table?
You can achieve it using MySQL stored procedure
Sample MySQL stored procedure
CREATE TABLE MyTable
(`ID` int, `ConditionField` varchar(10))
;
INSERT INTO MyTable
(`ID`, `ConditionField`)
VALUES
(1, 'Condition1'),
(1, 'Condition2')
;
CREATE PROCEDURE simpleproc (IN identifier INT,ConditionData varchar(10))
BEGIN
IF (SELECT ID FROM MyTable WHERE `ConditionField`=ConditionData) THEN
BEGIN
SELECT * FROM MyTable WHERE `ConditionField`=ConditionData;
END;
ELSE
BEGIN
INSERT INTO MyTable VALUES (identifier,ConditionData);
SELECT * FROM MyTable WHERE `ConditionField`=ConditionData;
END;
END IF;
END//
To Call stored procedure
CALL simpleproc(3,'Condition3');
DEMO

want to write trigger for two different databases in Mysql

Is there any way to create triggers on two different databases in Mysql? my requirement is like:-
database: test1 -> table: tmp1
database: test2 -> table: tmp2
now I have to use trigger on test1 insert operation happens on tmp1 a value has to be inserted into tmp2 of test2 database. And also vice a verse.
i.e. one more trigger on tmp2 table of test2 database, if insert into tmp2 then inserted into tmp1 table of test1 database.
I have tried to write the trigger on both but I think it will goes into loop to insert each other tables.
DELIMITER $$
CREATE TRIGGER trigger_ad_t1 AFTER insert ON `test1`.tmp1
FOR EACH ROW
Begin
INSERT INTO `test2`.tmp2 VALUES (NEW.employeeNumber,New.fname,New.lname)
END$$
DELIMITER ;
same type of trigger written for insert into tmp1 after insert into tmp2 table.
One more thing I have tested this trigger on my local pc which has mysql 5.1.63 but when I am trying this trigger on my testing server which has mysql 5.0.45 then it gives me syntax error(1064). Don't know what is the problem?
UPDATE:
Can anybody help me to get rid of it.
Thanks
Use fully qualified table names in your trigger.
I.e.
db1.test1.* and d2.test2.*
P.S. After looking at your SQL one more time I realised that you ARE doing the above already.
Edit: Comment field is to restrictive to post code, so here is how you prevent the endless insert loop (assuming employeeNumber is unique key):
Edited code:
IF NOT EXISTS(SELECT employeeNumber FROM otherDB.otherTable WHERE employeeNumber = NEW.employeeNumber) THEN
INSERT INTO otherDB.otherTable VALUES (NEW.employeeNumber,New.fname,New.lname)
END IF;
Correction was needed in the code provided originally:
... EXISTS(SELECT * FROM otherDB.otherTable ...) is replaced with
... EXISTS(SELECT employeeNumber FROM otherDB.otherTable ...)
The reason being that the first query will always return true because the inner query SELECT * FROM ... always returns one record containing the number of results =>
EXISTS(SELECT * FROM ...) is always true

mysql insertion where not exists syntax error. I have no idea what is wrong

insert into creditcard_info (member_id,card_type,card_number)
values ('1','Discover','555')
where not exists (
select * from creditcard_info
where card_number='555' and
card_type='Discover')
I want to be able to check if a card number already exists..
If card_number exists and card card_type exists then don't add
else insert this new card number along with card type
I am having difficultly with inserting into a table where a certain number does not exists.
Im getting this 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 'where not exists (select * from
creditcard_info where card_number='555')' at line 2
Thank you all in advance for helping me :)
It looks like you're trying to perform an INSERT ... SELECT statement.
However, adding a unique index in both fields should be more efficient.
You need to create a multi-column unique index. The code is as below:
ALTER TABLE creditcard_info ADD UNIQUE idx_card_number_card_type(card_number,card_type);
This should run as a separate query. And you need to add it once.
The other possible option is to add before insert trigger if the condition is more complicated than a simple unique check.
Here is the create trigger syntax:
Create Trigger card_type_unique_card_number_exists Before Insert on creditcard_info
FOR EACH ROW BEGIN
DECLARE it_exists INT;
Set it_exists=(select count(*) from creditcard_info where card_number='555' and card_type='Discover');
If it_exists>0 Then
#Throw a meaningful exception by let's say inserting into a table which doesn't exist or something
END IF;
END