Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL: Perform type conversion in BEFORE INSERT trigger
    primarykey
    data
    text
    <p>I have two tables, <code>pattern</code> and <code>pattern_optimized</code>. Some of the fields in the <code>pattern</code> table are defined as <code>BIGINT(20) DEFAULT '-1'</code>, which is way too big for the data they hold; Additionally, <code>-1</code> is used as "not set" (zero is a valid value) - no other negative values are used otherwise.</p> <p>The <code>pattern_optimized</code> table uses a new data format for these rows, defining them as <code>INT(10) UNSIGNED DEFAULT NULL</code>. I would now like to copy the data from <code>pattern</code> to the <code>pattern_optimized</code> table. </p> <p>This would be easily done using <code>INSERT INTO pattern_optimized SELECT * FROM pattern</code>, but obviously all negative values are out of range now, resulting in warnings like this:</p> <pre><code>100 row(s) affected, 64 warning(s): 1264 Out of range value for column 'version' at row 1 1264 Out of range value for column 'triggered' at row 1 ... Records: 100 Duplicates: 0 Warnings: 357 </code></pre> <p>My first idea was to create a <code>BEFORE INSERT</code> trigger as follows:</p> <pre><code>CREATE TRIGGER `negativeValueFix` BEFORE INSERT ON `pattern_optimized` FOR EACH ROW BEGIN IF new.version &lt; 0 THEN SET new.version = NULL; END IF; -- ... END </code></pre> <p>but unfortunately this doesn't help either: The same warning pops up and all values that used to be <code>-1</code> in the original table become <code>0</code> in the new table (instead of <code>NULL</code>, which is - apart from being implemented in the trigger - also the default for the row). It seems that MySQL converts the value even before the trigger.</p> <p>I know that I can solve this problem using a temporary table but I'd rather not do that. The <code>pattern</code> table is unpleasantly large and I don't want to do a stored procedure just for that.</p> <p>Is there any other way or am I missing some simple point?</p> <p><strong>EDIT</strong>: There are quite alot columns in the original table that suffer from the SIGNED problem, so I was hoping to somewhat automate that.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload