MySQL error with CAST and concatenation - mysql

Consider the below code
UPDATE users SET class = '-' + CAST(class AS CHAR(50)) + '-' WHERE 1=1
The above query throws the following error:
#1292 - Truncated incorrect DOUBLE value: '-'
I recently updated the class column from int(11) to varchar(255) and am trying to update every row to a format of: -class- where class is the previous int value.

if you have updated the column from int to varchar then there is no point casting it and just use CONCAT
UPDATE users SET class = CONCAT ('-',class,'-') WHERE 1=1
if class is NULL then the result will be NULL so to make sure you are only updating CLASS with values
UPDATE users SET class = CONCAT ('-',class,'-') WHERE class IS NOT NULL

Related

insert and remove multiple values in a table created with SET sql

I created a SET sql table, so a row can contain multiple values: Foo_1 Foo_2 Foo_3.
The above query run but it will update the the row and set just one value.
QueryType valid values are 1 2 or 3
"UPDATE Foo_status
SET type = 'Foo_%s',
status = %d
WHERE name ='%s'
", queryType.c_str(),status,GetName()
When i run the query: Let's assume that QueryType is 1, it's working.. my type row will have Foo_1, but when i run again the query and Foo has QueryType 2, it will remove Foo_1 and add Foo_2
How i can change my query so when i run the query it will continue to update values ?
Example:
Run Query
-Add Foo_1
Run Query
-Add Foo_2
Table struct
CREATE TABLE `Foo_status` (
`name` text NOT NULL,
`type` set('Foo_1','Foo_2','Foo_3') CHARACTER SET latin2 NOT NULL DEFAULT '',
`status` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I tried to search for an solution but without succes, that's i asked here.
Thanks!
Multiple set elements are specified using a comma-separated string. To add a new value, you have to concatenate a string beginning with comma.
"UPDATE Foo_status
SET type = CONCAT(type, ',Foo_%s'),
status = %d
WHERE name ='%s'
", queryType.c_str(),status,GetName()
To remove a value from a SET, use REPLACE():
"UPDATE Foo_status
SET type = REPLACE(type, 'Foo_%s', ''),
status = %d
WHERE name ='%s'
", queryType.c_str(),status,GetName()
It would be easier if you normalized your schema and used a table with a separate row for each type, instead of using the SET datatype. This would also allow you to add an index that would make searching for specific set values more efficient.
You can remove a set wirh this. Here written for select.
You can it also use for UPDATE.
You only must change the string to remove
select t,
trim( BOTH ',' FROM
replace (concat (',',t,','),',Foo_2,',',')) as new_t
from F;
Sample: http://www.sqlfiddle.com/#!9/a8b041/2

Truncated Inccorrect date value while calling nested function

I have two function.
fn_validate_date
fn_validation
fn_validate_date code:
CREATE DEFINER=`root`#`localhost` FUNCTION `fn_validate_date`(
`dt_date` DATE
)
RETURNS date
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Returns the associated value of given attribute for given employee for a particular date.'
BEGIN
SET dt_date = IF(dt_date IS NULL OR dt_date ='', CURRENT_DATE, dt_date);
RETURN dt_date;
END
fn_validation code:
CREATE DEFINER=`root`#`localhost` FUNCTION `fn_validation`(
`dt_date` DATE
)
RETURNS date
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
RETURN fn_validate_date(dt_date);
END
Now when I am calling fn_validate_date as below
SELECT `fn_validate_date`(null);
It's working well but when I calling fn_validation it's giving me an error.
SELECT `fn_validation`(null);
My question is why I didn't get error while calling fn_validate_date?
In fn_validate_date, the dt_date-parameter is type of date and you are comparing it to a string datatype. No need for that. Date datatype cannot contain ''. It either is NULL or has a date value in it.
So instead of:
SET dt_date = IF(dt_date IS NULL OR dt_date ='', CURRENT_DATE, dt_date);
You can simply use:
return ifnull( dt_date, current_date() );
I disable strict mode and it's working well.
SET sql_mode =''
To disable strict mode in MySQL. I am not sure why MySql short-circuited IF condition as I am passing NULL in the input parameter of fn_validation.

Mysql 1292: Truncated incorrect DOUBLE value

I'm getting this error after I added a generated column on my table.
The query is this:
UPDATE aspnetusers SET FirstName = 'somename' WHERE Id = 1;
FirstName column is varchar
Id column is int
Where is the db even getting this double?
This error started after I added this generated column:
"ALTER TABLE aspnetusers ADD FullName varchar(135) GENERATED ALWAYS AS (FirstName + ' ' + LastName) VIRTUAL;"
If I remove this column, then this error disappears.
Any thoughts?
Use CONCAT:
ALTER TABLE aspnetusers
ADD FullName varchar(135)
GENERATED ALWAYS AS (CONCAT(FirstName , ' ' , LastName)) VIRTUAL;
MySQL does not use + to concatenate strings. The error you get is caused by implicit conversion of strings to numbers.

Simple T-SQL function to convert date to displayable format

I have a strange bug that I cannot resolve (with a one line function).
This code works:
DECLARE #TestDate datetime = '2013-05-01 23:15:11'
select IsNull(convert(varchar(max), #TestDate, 120), 'null') as 'test1'
Displays: 2013-05-01 23:15:11
CREATE FUNCTION [dbo].[DateOrNullToChar] (#InputDate date)
RETURNS VARCHAR(40)
BEGIN
return ISNULL(convert(varchar(40),#InputDate, 120),'null');
END
select dbo.DateOrNullToChar('2013-05-01 23:15:11') as 'result'
Returns: 2013-05-01 (no time)
I have also tried varchar(max).
The purpose of the function is for something like this:
Set #ErrorMessage = ' #ArrivalDate=' + dbo.DateOrNullToChar(#ArrivalDate) +
' #DepartureDate=' + dbo.DateOrNullToChar(#DepartureDate);
If any one value is null, the whole value becomes null. So I want to see the string 'null' when a date has a null value.
#InputDate should be datetime or datetime2 if you want time to be shown
The clues are in the code...
#TestDate datetime
#InputDate date
You need to make the parameter type to be datetime instead of date:
CREATE FUNCTION [dbo].[DateOrNullToChar] (#InputDate datetime)
It's silently converting the string to your date parameter type and thus dropping the time portion.

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.