DROP PROCEDURE IF EXISTS kund2orderNew;
DELIMITER ;;
CREATE PROCEDURE kund2orderNew(kundId2 INT)
BEGIN
IF kundId2 <> (SELECT kundId FROM kund2order) THEN
INSERT INTO kundOrder VALUES ();
INSERT INTO kund2order VALUES (kundId2, (SELECT id FROM kundOrder));
END IF;
END
;;
DELIMITER ;
Alright am I doing something wrong here? What im trying to do is to check if kundId is in the kund2order, if its not then what I want to do is create a new row in the kundOrder table that just uses the default values and then take the recently created id from that row in the kundOrder and put it inside the new row in kund2order (together with kundId).
For some reason it just gives me (node:18328) UnhandledPromiseRejectionWarning: Error: ER_BAD_NULL_ERROR: Column 'kundId' cannot be null
I am a bit confused as to what the problem is, both tables are empty after I have called this procedure. Is the problem my if statement or is it something else?
That's not the correct way to check if an ID is already in the table. When you use a SELECT query as an expression, it has to return just one row. You can use:
IF NOT EXISTS (SELECT * FROM kund2Order WHERE kundId = kundId2) THEN
And if you want to insert the auto-increment of the row that was just inserted into kundOrder, you should use LAST_INSERT_ID():
INSERT INTO kund2order VALUES (kundId2, LAST_INSERT_ID());
Related
What is the error in the following code. I am executing in mysql
CREATE TRIGGER tg_order_insert
BEFORE INSERT
ON `order` FOR EACH ROW
BEGIN
INSERT INTO `grocery`.`order_seqid` VALUE(NULL);
SET NEW.order_id = CONCAT('#GNC', LPAD(LAST_INSERT_ID(),3,'0'));
END;
Grocery is the database and order_seqid and order are 2 table.
order_seqid is a table with only 1 attribute if type int and auto increment.
Am trying to put a prefix on the id which we insert into order table.
I am getting 2 errors in INSERT INTO..... and END; line
Did you declare a delimiter before your trigger definition? Something like
DELIMITER //
CREATE TRIGGER tg_order_insert
BEFORE INSERT
ON `order` FOR EACH ROW
BEGIN
INSERT INTO `grocery`.`order_seqid` VALUE(NULL);
SET NEW.order_id = CONCAT('#GNC', LPAD(LAST_INSERT_ID(),3,'0'));
END
//
Because if you don't, then MySQL thinks you're trying to end your trigger definition when it sees that first ; and calls syntax error.
USE test;
CREATE TRIGGER AvgUpdateTrigger AFTER INSERT ON test.score
FOR EACH ROW
BEGIN
INSERT INTO test.average (test.average.TestID, test.average.TestAvg)
(SELECT test.score.TestID, avg(test.score.ScoreValue) FROM test.score GROUP BY test.score.TestID)
ON DUPLICATE KEY
UPDATE test.average.TestAvg = (SELECT avg(test.score.ScoreValue) FROM test.score WHERE test.score.TestID = test.average.TestID GROUP BY test.score.TestID);
END;
im trying to update one table(average) when another one gets changed(score)
it is telling me to add a semicolon but as you can see there is one there allready
If a trigger (or any stored procedure) contains only one statement, you don't need BEGIN and END:
CREATE TRIGGER AvgUpdateTrigger AFTER INSERT ON test.score
FOR EACH ROW
INSERT INTO test.average (TestID, TestAvg)
SELECT test.score.TestID, avg(test.score.ScoreValue)
FROM test.score
GROUP BY test.score.TestID
ON DUPLICATE KEY UPDATE
test.average.TestAvg = VALUES(TestAvg);
I also replaced the subquery with VALUES(TestAvg), since this value has already been selected.
I have a table which contain some fields(id,code,name,...), when I want to insert new record the code field should be like (ABC-001) and next record should be like (ABC-002) and so on.
I want to write a MYSQL procedure for this but I don't know how, any body has any idea? thanks in advance
First User Insert Query like:
Insert Into YourTable Values(..,'ABC',...);
Now write trigger after update which set Code value in expected format:
CREATE TRIGGER TriggerNmae AFTER INSERT ON YourTable
FOR EACH ROW
Begin
UPDATE YourTable
SET code = concat(code,'-',LPAD(NEW.id,3,'0'));
WHERE id = New.id ;
END;
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
I'm trying to create a trigger, however I keep getting back a syntax error.
Here's the statement:
DELIMITER $$
CREATE TRIGGER `swtalentbank`.`after_candidate_insert`
AFTER INSERT ON `Candidates` FOR EACH ROW
BEGIN
INSERT INTO useradmin (username, talent)
VALUES (NEW.email, 1);
UPDATE `Candidates` SET UserID = useradmin.userid where useradmin.username = NEW.email;
END
DELIMITER ;
I have a registration form on my site. When a person registers it populates the Candidates table with their profile information.
In the Candidates table, there are various fields, two of them being 'email' and 'UserID'.
UserID is also the PK in 'useradmin', so I'm linking the two up.
So when a user registers, I need to insert a record into 'useradmin' with the email address that's just been used to register, and then update the 'Candidates' table, with UserID that's just been created in 'useradmin'.
I hope this makes sense?
NB. I am changing the delimiter before running the statement.
Besides properly using DELIMITER when creating a trigger you have at least two fundamental issues with your current code:
In MySQL you can't use issue a DML statement (in your case UPDATE) against a table (candidates) on which you defined a trigger (also candidates). Your only option is to use BEFORE trigger and set a value of userid column of a row being inserted to a proper value.
You can't arbitrarily reference a column (useradmin.userid) of a table out of the context like you did in your UPDATE. You didn't joined useradmin table or used it in a subquery.
That being said and assuming that userid in useradmin table is an auto_increment column your trigger might look like this
DELIMITER $$
CREATE TRIGGER after_candidate_insert
BEFORE INSERT ON candidates
FOR EACH ROW
BEGIN
INSERT INTO useradmin (`username`, `talent`) VALUES (NEW.email, 1);
SET NEW.userid = LAST_INSERT_ID();
END$$
DELIMITER ;
Here is SQLFiddle demo
You should use semicolon after end your insert query.
You can use INSERT ... ON DUPLICATE KEY UPDATE syntax for your purpose
try out this...
DELIMITER $$
CREATE TRIGGER `swtalentbank`.`after_candidate_insert`
AFTER INSERT ON `Candidates` FOR EACH ROW
BEGIN
INSERT INTO useradmin (username, talent)
VALUES (NEW.email, 1);
UPDATE `Candidates` SET UserID = useradmin.userid where useradmin.username = NEW.email;
END $$
DELIMITER ;