MySql update query not working-generic error - mysql

I get a generic error message, and have no idea what the problem is with the query. What do I do to fix this?
Query explanation: there are two tables, Invoice, and temp. I need to take zip codes from temp table and push them to the Invoice table, based on the invoice number.
START TRANSACTION
UPDATE
Invoice
SET
Invoice.zip_code = (SELECT zip_code FROM temp WHERE temp.invoice_number = Invoice.invoice_number)
WHERE
Invoice.invoice_date >= '2017-08-01'
ROLLBACK
this is the error:
Error Code: 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 'UPDATE Invoice SET Invoice.zip_code = (SELECT
zip_code FROM temp WHERE temp' at line 3

Add semicolon after each command.
START TRANSACTION;
UPDATE
Invoice
SET
Invoice.zip_code = (SELECT zip_code FROM temp WHERE temp.invoice_number = Invoice.invoice_number)
WHERE
Invoice.invoice_date >= '2017-08-01';
ROLLBACK;

Sounds like #Daniel Blais is right. One thing you can do to troubleshoot is to break the query down and run each part individually. That will help you find out what's wrong.
SELECT zip_code FROM temp WHERE temp.invoice_number = Invoice.invoice_number;
One other question: Why are you rolling back after the table is updated? Don't you want to commit?

Related

A variable is cut in a wrong way but now sure why?

I'm writing a script that locates all branches of a specific repo that haven't received any commits for more than 6 months and deletes them (after notifying committers).
This script will run from Jenkins every week, will store all these branches in some MySQL database and then in the next run (after 1 week), will pull the relevant branch names from the database and will delete them.
I want to make sure that if for some reason the script is run twice on the same day, relevant branches will not get added again to the database, so I check it using a SQL query:
def insert_data(branch_name):
try:
connection = mysql.connector.connect(user=db_user,
host=db_host,
database=db_name,
passwd=db_pass)
cursor = connection.cursor(buffered=True)
insert_query = """insert into {0}
(
branch_name
)
VALUES
(
\"{1}\"
) where not exists (select 1 from {0} where branch_name = \"{1}\" and deletion_date is NULL) ;""".format(
db_table,
branch_name
)
cursor.execute(insert_query, multi=True)
connection.commit()
except Exception as ex:
print(ex)
finally:
cursor.close()
connection.close()
When I run the script, for some reason, the branch_name variable is cut in the middle and then the query that checks if the branch name already exists in the database fails:
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 'where not exists (select 1 from branches_to_delete where branch_name = `AUT-1868' at line 8
So instead of checking for 'AUT-18681_designer_create_new_name_if_illegal_char_exist' it checks for 'AUT-1868' which doesn't exist in the database.
I've tried the following:
'{1}'
"{1}"
{1}
But to no avail.
What am I doing wrong?
Using WHERE statement in INSERT INTO query is illegal:
INSERT INTO `some_table`(`some_column`)
VALUES ('some_value') WHERE [some_condition]
So, the above example is not valid MySQL query. For prevent duplication of branch_name you should add unique index on your table like:
ALTER TABLE `table` ADD UNIQUE INDEX `unique_branch_name` (`branch_name`);
And after this you can use next query:
INSERT INTO `table` (`branch_name`) VALUES ('branch_name_1')
ON DUPLICATE KEY UPDATE `branch_name` = `branch_name`;
Pay attention: If your table have auto-increment id, it will be incremented on each insert attempt
Since MySQL 8.0 you can use JASON_TABLE function for generate pseudo table from your values filter it from already exists values and use it fro insert. Look here for example
I don't see anything wrong assuming the source of the branch_name is safe (you are not open to SQL Injection attacks), but as an experiment you might try:
insert_query = f"""insert into {db_table}(branch_name) VALUES(%s) where not exists
(select 1 from {db_table} where branch_name = %s and deletion_date is NULL)"""
cursor.execute(insert_query, (branch_name, branch_name))
I am using a prepared statement (which is also SQL Injection-attack safe) and thus passing the branch_name as a parameters to the execute method and have also removed the multi=True parameter.
Update
I feel like a bit of a dummy for missing what is clearly an illegal WHERE clause. Nevertheless, the rest of the answer suggesting the use of a prepared statement is advice worth following, so I will keep this posted.

Multiple Queries in Triggers

I'm fairly new to using triggers and have a tiny question.
I have a trigger finds a match between a newly inserted enquiry and a customer table.
INSERT INTO customersmatched (customerID,enquiryID) SELECT id, NEW.id FROM customer AS c WHERE c.customerName=NEW.companyName HAVING COUNT(id)=1;
I then need to update the newly inserted enquiry so it has a status which shows it's matched (but only if it has matched). So I tried adding this line after the insert.
UPDATE enquiry SET status="Live-Enquiry" WHERE id IN ( SELECT enquiryID FROM customersmatched WHERE enquiryID = NEW.id);
Except I get this error:
MySQL said: #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 'UPDATE enquiry SET status="Live-Enquiry" WHERE id
IN ( SELECT enquiryID FROM cus' at line 5
How do I allow multiple queries within a trigger. I've tried doing something like in this link: Multiple insert/update statements inside trigger?
But doesn't work either. I'm using phpmyadmin btw. Can anyone help? :D
If you have ansi quotes enabled then you can't use double quotes as a string literal, and need to use single quotes instead. see: http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_ansi_quotes Otherwise, I don't see any syntax errors that jump out at me.
Try changing SET status="Live-Enquiry" to SET status='Live-Enquiry'
EDIT:
What is the purpose of the first query? I'm not sure you need the HAVING in that query. If want a distinct list of matches, just use DISTINCT
INSERT INTO customersmatched (customerID,enquiryID)
SELECT DISTINCT id, NEW.id
FROM customer AS c
WHERE c.customerName=NEW.companyName;
The second query, if I understand it correctly, can be simplified to this:
UPDATE enquiry
SET status='Live-Enquiry'
WHERE id = NEW.id;

MySQL Workbench error 1305 PROCEDURE doesn't exist

I'm trying to execute a statment in MySql to update a column in a table when the expiry date for one of the other columns surpasses the current date, this is then compared against something to make sure that there are no active people for it
but i keep getting this error , i can not see anything wrong with my syntax so im not sure what it is
Error 1305 PROCEDURE does not exist
UPDATE job j SET archived = 1 WHERE(SELECT count(*) FROM job_applied_candidates jac WHERE jac.jobID = j.id) = 0 AND enddate < now();
Add a space between WHERE an (Select...
Also check triggers on jobs table, since they could use a procedure that does not exist.

Mysql Updating with if condition within a Table

I am unable to update 2 fields in a Table using UDPATE AND IF condition. Need help.
I have an invoice table where in If field Nos=0 I need to update field Qty from Capacity and field Nos=1 in the same table.
My sql statement is not working:
UPDATE INVDTLS_draft1 SET `Nos`=1, `Qty`=`Capacity` IF (Nos=0) WHERE id=id
error message:
#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 (Nos=0) WHERE id=id' at line 1
try this query, using AND operator
UPDATE INVDTLS_draft1 SET `Nos`=1, `Qty`=`Capacity` WHERE id=id AND Nos=0
Why id=id? I think you need this:
UPDATE INVDTLS_draft1
SET `Nos`=1, `Qty`=`Capacity`
WHERE Nos=0
Try this:
UPDATE INVDTLS_draft1 SET
Nos=1,
Qty = if(nos=0, capacity, Qty)
WHERE id=?
This "does nothing" to qty if nos != 0.

MySQL foreign key problem

I'm getting that error running on MySQL 5.5.8
Mysql2::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
(SELECT id FROM products WHERE id = NEW.brand_id) IS NULL;
EN' at line 6:
CREATE TRIGGER fk_brands_products_insert
BEFORE INSERT ON brands
FOR EACH ROW BEGIN
SELECT
RAISE(ABORT, "constraint violation: fk_brands_products")
WHERE
(SELECT id FROM products WHERE id = NEW.brand_id) IS NULL;
END;
What could be wrong?
I suspect the problem is there is no FROM clause in your select statement.
Are you sure you can raise errors inside a query like that? I can't find it anywhere. I think the proper way would be to select a COUNT or EXISTS and return the result of that INTO a variable. Then, after the query, raise an error if the result doesn't meet your expectations.
Something like this:
SELECT count(id) INTO IDCOUNT FROM products WHERE id = NEW.brand_id;
Wouldn't it be better by the way to just add a real constraint? Or do you use a storage type that doesn't support that?