mysql different row updates depending on a variable (stored procedure) - mysql

CREATE PROCEDURE update_table(
IN choice INT(4),
IN id VARCHAR(50),
IN string VARCHAR(50)
)
BEGIN
UPDATE salesman
set salesman_name = IF(choice = 1, string, salesman_name)
where salesman_id = id
UPDATE salesman
set date = IF(choice = 2, string, date)
where salesman_id = id
END
if choiceis 1, change salesman_name as string
if choice is 2, change date as string
can you explain me what i'm doing wrong?
it works fine with a single update, my guess is there is another way to implement if but i couldn't.
if choice = 1 then
update salesman set salesman_name = string where salesman_id = id
...i tried this version too but still, not working.
DELIMITER //
CREATE PROCEDURE update_table(
IN choice INT(4),
IN id VARCHAR(50),
IN string VARCHAR(50)
)
BEGIN
UPDATE salesman set salesman_name = IF(choice = 1, string, salesman_name) where salesman_id = id;
UPDATE salesman set date = IF(choice = 2, string, date) where salesman_id = id;
END //
DELIMITER ;
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 'DELIMITER' at line 1
also says this:
ERROR: Unknown Punctuation String # 11 (last line)

When a stored procedure has more than one statement, they need to be terminated with ;
To do that, you need to tempoararily change the delimiter so you can end the procedure. Here's a SO answer with an example of how to do that: MySQL create stored procedure syntax with delimiter

Related

Error in creating procedure in MySQL

What may be the possibilities of getting an error in the following query?
DELIMITER $$
CREATE PROCEDURE `tbl_assessment_notes`(
`var_reason` VARCHAR,
'var_attr2' VARCHAR,
'var_note' VARCHAR
)
BEGIN
IF EXISTS
(
SELECT
*
FROM
tbl_assessment_notes
WHERE
reason = var_reason AND attr2 = var_attr2
) THEN
UPDATE
tbl_assessment_notes
SET
note = CONCAT(note, var_note),
TIMESTAMP = 'CURRENT_TIMESTAMP'
WHERE
attr1 = var_attr1 AND reason = var_reason ELSE
INSERT
INTO
tbl_assessment_notes(
pk_assess_note_id,
attr2,
attr3,
reason,
note,
TIMESTAMP
)
VALUES(
NULL,
var_attr2,
NULL,
'confirmation',
var_note,
'CURRENT_TIMESTAMP'
) ;
END IF ;
END $$
DELIMITER ;
I'm getting the following 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 '
'var_reason' VARCHAR,
'var_attr2' VARCHAR,
`var_note` VARCHAR,
'var' at line 2
Basically what I'm trying to do is to update a row if it exists or else creates a new row and insert values into it.
Please use updated query
DELIMITER $$
CREATE PROCEDURE `tbl_assessment_notes`
(var_reason VARCHAR(255),
var_attr2 VARCHAR(255),
var_note VARCHAR(255))
BEGIN
IF EXISTS
(
SELECT
*
FROM
tbl_assessment_notes
WHERE
reason = var_reason AND attr2 = var_attr2 ) THEN UPDATE tbl_assessment_notes SET note = CONCAT(note, var_note), TIMESTAMP
= 'CURRENT_TIMESTAMP' WHERE attr1 = var_attr1 AND reason = var_reason ELSE INSERT INTO tbl_assessment_notes(
pk_assess_note_id,
attr2,
attr3,
reason,
note,
TIMESTAMP) VALUES(NULL,var_attr2,NULL,'confirmation', var_note, 'CURRENT_TIMESTAMP' ) ;
END IF ;
END $$
DELIMITER ;

Query always returns 1064 syntax error

I use 'MariaDB 5.5 x64' and Client HeidiSQL.
server environment is Windows Server2012 Datacenter.
And database use_progress a row is following
int id //auto-incremental primary key
int owner //owner user's unique id
varchar[20] name //key
int value //value
it stores online game user's states key-value type
for example
id owner name value
856 656 stage0cleared 0
857 656 have_gold 10214
858 657 inventory 22
and the next query's working test is fine
select count(*) from use_progress where owner = 656 and name = "inventory";
INSERT INTO use_progress (use_progress.owner, use_progress.name, use_progress.value) VALUES (656, 'inventory', 7);
UPDATE use_progress SET use_progress.value = 7 WHERE use_progress.`owner` = 656 AND use_progress.`name` = 'inventory';
but the next query is error 1064 (syntax error)
BEGIN
IF ((select count(*) from use_progress where owner = 656 and name = "inventory") = 0 ) THEN
INSERT INTO use_progress (use_progress.owner, use_progress.name, use_progress.value) VALUES (656, 'inventory', 7);
ELSE
UPDATE use_progress SET use_progress.value = 7 WHERE use_progress.`owner` = 656 AND use_progress.`name` = 'inventory';
END IF;
END
the error is folling next(always that error):
/* 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 'IF ((select count(*) from use_progress where owner = 656 and name = "inventory")' at line 2 */
I tried everything I could. Use () or not, insert dbname.tablename. prefix to every column name or not. But in every situation, the same error occurs.
I even tried this (line 2 is changed):
BEGIN
IF (1>2) THEN
INSERT INTO use_progress (use_progress.owner, use_progress.name, use_progress.value) VALUES (656, 'inventory', 7);
ELSE
UPDATE use_progress SET use_progress.value = 7 WHERE use_progress.`owner` = 656 AND use_progress.`name` = 'inventory';
END IF;
END
But same error occurs (message is same)
I don't know why this happen.
You can't use control structures like IF() THEN ... in simple queries, only in stored procedures or functions.
In this case you'd use a stored procedure. Try like this:
DELIMITER $$
CREATE PROCEDURE my_proc_name(IN p_owner int, IN p_name varchar(50), IN p_value int)
BEGIN
IF NOT EXISTS (select 1 from use_progress where owner = p_owner and name = p_name) THEN
INSERT INTO use_progress (owner, name, `value`) VALUES (p_owner, p_name, p_value);
ELSE
UPDATE use_progress SET `value` = p_value WHERE `owner` = p_owner AND `name` = p_name;
END IF;
END $$
DELIMITER ;
After creating it, you'd call it like this:
CALL my_proc_name(656, 'inventory', 7);

Get the Unique ID for the Last Inserted Row

I want to get the Unique ID for the Last Inserted Row inside stored procedure, I make like this
DELIMITER //
CREATE PROCEDURE addNewUsers(IN userName varchar(128),IN password varchar(128), IN addedBy INT)
BEGIN
DECLARE id int default 0;
id = mysqli_insert_id (insert into `system_users`( `username`,`password`) values (userName ,md5(password)) );
IF id <> 0 THEN
insert into `user_profile`( `full_name`,`Date_time_ added`,`added_by`) values (userName ,CURRENT_TIMESTAMP(),addedBy ) where `user_id`=id ;
END IF
END //
DELIMITER ;
This error occur
#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 '= mysqli_insert_id (insert into `system_users`( `username`,`password`) values (' at line 7
I doubt it's from mysqli_insert_id , what should I do ?
Your mysqli_insert_id is the problem, you're writing a MySQL stored procedure, not PHP. You want to use the last_insert_id() function:
LAST_INSERT_ID() (with no argument) returns a BIGINT (64-bit) value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement.
You also need to fix your assignment syntax. Something more like this:
DELIMITER //
CREATE PROCEDURE addNewUsers(IN userName varchar(128),IN password varchar(128), IN addedBy INT)
BEGIN
DECLARE id int default 0;
insert into `system_users`( `username`,`password`) values (userName ,md5(password));
set id = last_insert_id();
if id <> 0 then
-- ...

Mysql stored function help needed

I'm just beginning to learn stored functions in mysql. Can someone please tell me whats wrong with below?
Phpmyadmin says 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 'return NAME;
END //' at line 19
DELIMITER //
DROP FUNCTION IF EXISTS getName //
CREATE FUNCTION getName(type CHAR(10), id int) RETURNS CHAR(50) DETERMINISTIC
BEGIN
DECLARE NAME CHAR(50);
CASE type
WHEN 'offer' THEN
SELECT Type_Name INTO NAME FROM otypes WHERE Type_Id = id;
WHEN 'service' THEN
SELECT ServiceType_Name INTO NAME FROM stypes WHERE ServiceType_Id = id;
WHEN 'store' THEN
SELECT Store_Name INTO NAME FROM stores WHERE Store_Id = id;
END CASE
return NAME;
END //
Put a semicolon after END CASE:
DELIMITER //
DROP FUNCTION IF EXISTS getName //
CREATE FUNCTION getName(type CHAR(10), id int) RETURNS CHAR(50) DETERMINISTIC
BEGIN
DECLARE NAME CHAR(50);
CASE type
WHEN 'offer' THEN
SELECT Type_Name INTO NAME FROM otypes WHERE Type_Id = id;
WHEN 'service' THEN
SELECT ServiceType_Name INTO NAME FROM stypes WHERE ServiceType_Id = id;
WHEN 'store' THEN
SELECT Store_Name INTO NAME FROM stores WHERE Store_Id = id;
END CASE;
-- ^
return NAME;
END //
You missing a ;
END CASE
return NAME;
should be
END CASE;
return NAME;

MYSQL Truncated incorrect DOUBLE value

When the SQL query below is executed:
UPDATE shop_category
SET name = 'Secolul XVI - XVIII'
AND name_eng = '16th to 18th centuries'
WHERE category_id = 4768
The following error is raised:
1292 - Truncated incorrect DOUBLE value: 'Secolul XVI - XVIII'
How to fix this?
shop_category table structure:
category_id mediumint(8)
name varchar(250)
name_eng varchar(250)
You don't need the AND keyword. Here's the correct syntax of the UPDATE statement:
UPDATE
shop_category
SET
name = 'Secolul XVI - XVIII',
name_eng = '16th to 18th centuries'
WHERE
category_id = 4768
I was getting this exception not because of AND instead of comma, in fact I was having this exception just because I was not using apostrophes in where clause.
Like my query was
update table set coulmn1='something' where column2 in (00012121);
when I changed where clause to where column2 in ('00012121'); then the query worked fine for me.
What it basically is
It's incorrect syntax that causes MySQL to think you're trying to do something with a column or parameter that has the incorrect type "DOUBLE".
Learn from my mistake
In my case I updated the varchar column in a table setting NULL where the value 0 stood. My update query was like this:
UPDATE myTable SET myValue = NULL WHERE myValue = 0;
Now, since the actual type of myValue is VARCHAR(255) this gives the warning:
+---------+------+-----------------------------------------------+
| Level | Code | Message |
+---------+------+-----------------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: 'value xyz' |
+---------+------+-----------------------------------------------+
And now myTable is practically empty, because myValue is now NULL for EVERY ROW in the table! How did this happen?
*internal screaming*
Over 30k rows now have missing data.
*internal screaming intensifies*
Thank goodness for backups. I was able to recover all the data.
*internal screaming intensity lowers*
The corrected query is as follows:
UPDATE myTable SET myValue = NULL WHERE myValue = '0';
^^^
Quotation here!
I wish this was more than just a warning so it's less dangerous to forget those quotes.
*End internal screaming*
Try replacing the AND with ,
UPDATE shop_category
SET name = 'Secolul XVI - XVIII', name_eng = '16th to 18th centuries'
WHERE category_id = 4768
The UPDATE Syntax shows comma should be used as the separator.
Mainly invalid query strings will give this warning.
Wrong due to a subtle syntax error (misplaced right parenthesis) when using INSTR function:
INSERT INTO users (user_name) SELECT name FROM site_users WHERE
INSTR(status, 'active'>0);
Correct:
INSERT INTO users (user_name) SELECT name FROM site_users WHERE
INSTR(status, 'active')>0;
I just wasted my time on this and wanted to add an additional case where this error presents itself.
SQL Error (1292): Truncated incorrect DOUBLE value: 'N0003'
Test data
CREATE TABLE `table1 ` (
`value1` VARCHAR(50) NOT NULL
);
INSERT INTO table1 (value1) VALUES ('N0003');
CREATE TABLE `table2 ` (
`value2` VARCHAR(50) NOT NULL
);
INSERT INTO table2 (value2)
SELECT value1
FROM table1
WHERE 1
ORDER BY value1+0
The problem is ORDER BY value1+0 - type casting.
I know that it does not answer the question but this is the first result on Google for this error and it should have other examples where this error presents itself.
It seems mysql handles the type casting gracefully with SELECT statements.
The shop_id field is of type varchar but the select statements works
select * from shops where shop_id = 26244317283;
But when you try updating the fields
update stores set store_url = 'https://test-url.com' where shop_id = 26244317283;
It fails with error Truncated incorrect DOUBLE value: '1t5hxq9'
You need to put the shop_id 26244317283 in quotes '26244317283' for the query to work since the field is of type varchar not int
update stores set store_url = 'https://test-url.com' where shop_id = '26244317283';
1292 - Truncated incorrect DOUBLE value:
This error occurs when you try to compare different types on SQL like `uniqueid` = 1610386969.1713 in this query:
UPDATE `cdr` SET `userfield`='survey=5,' WHERE `uniqueid` = 1610386969.1713
change it for passing the error on this UPDATE example:
UPDATE `cdr` SET `userfield`='survey=5,' WHERE `uniqueid` = '1610386969.1713'
But in your problem, if you change the AND to , the problem will be resolved
UPDATE shop_category SET name = 'Secolul XVI - XVIII', name_eng = '16th to 18th centuries' WHERE category_id = 4768
This is because of "and" in-between while using update query
WRONG ==> "update user_detail set name = ? and phone_code = ? and phone_num = ? and email = ? where emp_code = ?";
instead of this use COMMA(,)
RIGHT ==> "update user_detail set name = ?, phone_code = ?, phone_number = ?, email = ? where emp_code = ?"
If you're getting this problem with an insert that looks like the one below, the problem may simply be the lack of a space between -- and the comment text:
insert into myTable (a, b, c)
values (
123 --something
,345 --something else
,567 --something something else
);
The problem with this is that the --something should actually be -- something with a space.
I experienced this error when using bindParam, and specifying PDO::PARAM_INT where I was actually passing a string. Changing to PDO::PARAM_STR fixed the error.
I did experience this error when I tried doing an WHERE EXIST where the subquery matched 2 columns that accidentially was different types.
The two tables was also different storage engines.
One column was a CHAR (90) and the other was a BIGINT (20).
One table was InnoDB and the other was MEMORY.
Part of query:
[...] AND EXISTS (select objectid from temp_objectids where temp_objectids.objectid = items_raw.objectid );
Changing the column type on the one column from BIGINT to CHAR solved the issue.
// CALL `ut_liquid_name_maildt`() Edit
// Truncated incorrect DOUBLE value: 'IPPAGUNTA VIJAYALAKSHMI'
// Code Sample
BEGIN
-- Declare loop constructs --
DECLARE done INT DEFAULT FALSE;
DECLARE my_id VARCHAR(50);
DECLARE my_name VARCHAR(50);
DECLARE my_mail_dt date;
DECLARE my_name_gl VARCHAR(50);
DECLARE my_mail_dt_gl VARCHAR(50);
-- cursor --
declare cr cursor for select t2.id,t1.name,t1.mail_dt,t2.name as name_gl,t2.mail_dt as mail_dt_gl
from sch_acc_saleint as t1
inner join
sch_acc_salegl as t2
where t1.sch_batch = t2.sch_batch;
-- Declare Continue Handler --
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cr;
read_loop: LOOP
-- Fetch data from cursor --
FETCH cr
INTO my_id,my_name,my_mail_dt,my_name_gl,my_mail_dt_gl;
-- Exit loop if finished --
IF done THEN
LEAVE read_loop;
END IF;
-- Update Query --
UPDATE sch_acc_salegl SET name = my_name and mail_dt = my_mail_dt WHERE id = my_id;
END LOOP read_loop;
CLOSE cr;
END
// I was using wrong update query that"s why it is showing error [ Truncated incorrect DOUBLE value ]
// For this type of error check update query
// For example :
UPDATE sch_acc_salegl SET name = my_name,mail_dt = my_mail_dt WHERE id = my_id;
In my case it was a Dreamweaver function that sanitizes the data before running mysql queries:
GetSQLValueString($my_string, "text")
by mistake I had it as:
GetSQLValueString($my_string, "int")
Basically converting my string to an integer then trying to run MySQL queries based on that. When it should have been a string.
So using "int" instead of "text" caused the problem for me.