Failed generated stored procedure - mysql

This is the code
CREATE TABLE `church` (
`ID` int(10) UNSIGNED NOT NULL,
`StudentID` int(11) NOT NULL,
`semesterID` int(11) NOT NULL,
`attendedWed` int(11) NOT NULL,
`attendedFri` int(11) NOT NULL,
`attendedSabM` int(11) NOT NULL,
`attendedSabE` int(11) NOT NULL,
`ChurchScore` double(10,2) GENERATED ALWAYS AS ((((((`attendedWed` + `attendedFri`) + `attendedSabM`) + `attendedSabE`) * 100) / 60)) STORED
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
This is the error
Operation failed: There was an error while applying the SQL script to
the database. Executing: ALTER TABLE citizenshipgroup3.church
CHANGE COLUMN ChurchScore ChurchScore DOUBLE(10,2) NULL DEFAULT
attendedWed ;
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 'attendedWed' at line 2 SQL Statement: ALTER TABLE
citizenshipgroup3.church CHANGE COLUMN ChurchScore
ChurchScore DOUBLE(10,2) NULL DEFAULT attendedWed

Your syntax is fine. The problem is that MySQL does not support generated columns until 5.7. You are presumably using an earlier version.
Probably the simplest solution is to use a view for the calculation.

The error appears at the time of ALTER TABLE, when you are trying to modify the column ChurchScore setting the DEFAULT value to an expression involving another Column attendedWed.
Also, your error message seems to be originating from MariaDB, not MySQL.
From Mariadb Documentation:
From MariaDB 10.2.1 you can use most functions in DEFAULT. Expressions
should have parentheses around them. If you use a non deterministic
function in DEFAULT then all inserts to the table will be replicated
in row mode. You can even refer to earlier columns in the DEFAULT
expression:
CREATE TABLE t1 (a int DEFAULT (1+1), b int DEFAULT (a+1));
CREATE TABLE t2 (a bigint primary key DEFAULT UUID_SHORT());
So you need to ensure couple of things:
Upgrade your MariaDB version to 10.2.1 and above. Preferably, upgrade to current latest version (it is 10.3+ right now).
You need to use parentheses around the expression specified in the DEFAULT clause.
So the ALTER TABLE statement would look like:
ALTER TABLE `citizenshipgroup3`.`church`
CHANGE COLUMN `ChurchScore` `ChurchScore` DOUBLE(10,2) NULL
DEFAULT (attendedWed) ;

Related

MySQL Workbench create table generates SQL that throws an error

I am using MySQL version 5.7.18 and MySQL Workbench is targeting version 5.6.20. However, when I try and create a table using the table generator it produces the following sql statement:
CREATE TABLE `sys`.`annotations` (
`id` INT GENERATED ALWAYS AS () VIRTUAL,
`annotation` LONGTEXT NOT NULL,
PRIMARY KEY (`id`));
But this produces the following error message:
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 ') STORED',
`annotation` LONGTEXT NOT NULL,
PRIMARY KEY (`id`))' at line 2
SQL Statement:
CREATE TABLE `sys`.`annotations` (
`id` INT GENERATED ALWAYS AS () STORED,
`annotation` LONGTEXT NOT NULL,
PRIMARY KEY (`id`))
Why would this be happening and how would I go about fixing this?
I have no idea what an empty expression means for a computed column. Nor do I understand a VIRTUAL column being a primary key. I would use:
CREATE TABLE sys.`annotations` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`annotation` LONGTEXT NOT NULL
);

mysql can not insert because no default value?

I have two tables with exactly the same schema. I can insert into one table but not another. The one that fails complains about no default value. Here's my create statement for the table
CREATE TABLE `t_product` (
`product_id` varchar(10) NOT NULL,
`prod_name` varchar(150) DEFAULT NULL,
`price` decimal(6,2) NOT NULL,
`prod_date` date NOT NULL,
`prod_meta` varchar(250) DEFAULT NULL,
`prod_key` varchar(250) DEFAULT NULL,
`prod_desc` varchar(150) DEFAULT NULL,
`prod_code` varchar(12) DEFAULT NULL,
`prod_price` decimal(6,2) NOT NULL,
`prod_on_promo` tinyint(1) unsigned NOT NULL,
`prod_promo_sdate` date DEFAULT NULL,
`prod_promo_edate` date DEFAULT NULL,
`prod_promo_price` decimal(6,2) NOT NULL,
`prod_discountable` tinyint(1) unsigned NOT NULL,
`prod_on_hold` tinyint(1) unsigned NOT NULL,
`prod_note` varchar(150) DEFAULT NULL,
`prod_alter` varchar(150) DEFAULT NULL,
`prod_extdesc` text,
`prod_img` varchar(5) NOT NULL,
`prod_min_qty` smallint(6) unsigned NOT NULL,
`prod_recent` tinyint(1) unsigned NOT NULL,
`prod_name_url` varchar(150) NOT NULL,
`upc_code` varchar(50) DEFAULT NULL,
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
When I run this statement in database1, it successfully inserts:
insert into t_product (product_id) values ('jlaihello');
When I run this exact statement in database2, I get the error:
ERROR 1364 (HY000): Field 'price' doesn't have a default value
Why is this error happening only in database2? As far as I can tell, the difference between database1 and database2 are:
database1 uses mysql Ver 14.14 Distrib 5.5.53, for debian-linux-gnu (i686) using readline 6.3
and
database2 uses mysql Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using EditLine wrapper
How do I make database2 behave like database1?
EDIT
There are hundreds of tables affected by this. Basically we're moving a database over to a new server. And I did a mysqldump from db1, and imported into db2. t_product is just ONE of the tables affected by this. I'd like to avoid manually modifying the schema for the hundreds of tables. I prefer a "simple switch" that will make db2 behave like db1.
ERROR 1364 (HY000): Field 'price' doesn't have a default value
price decimal(6,2) NOT NULL,
Set price to null or assign a default value
EDIT:
This is caused by the STRICT_TRANS_TABLES SQL mode.
Open phpmyadmin and goto More Tab and select Variables submenu. Scroll down to find sql mode. Edit sql mode and remove STRICT_TRANS_TABLES Save it.
OR
You can run an SQL query within your database management tool, such as phpMyAdmin:
-- verify that the mode was previously set:
SELECT ##GLOBAL.sql_mode;
-- update mode:
SET ##GLOBAL.sql_mode= 'YOUR_VALUE';
OR
Find the line that looks like so in the mysql conf file:
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
Comment above line out and restart mysql server
Most probably, the default for column price is missing in the second database. To check this you should output your table structure:
describe database2.t_product;
OR
show create table database2.t_product;
and check if the default is defined.
You can alter your table and add the missing default constraint like this:
ALTER TABLE database2.t_product MODIFY COLUMN decimal(6,2) NOT NULL DEFAULT 0
EDIT
Based on comments and specification (data type default values), I think there is a difference in sql_mode of the MySQL:
For data entry into a NOT NULL column that has no explicit DEFAULT
clause, if an INSERT or REPLACE statement includes no value for the
column, or an UPDATE statement sets the column to NULL, MySQL handles
the column according to the SQL mode in effect at the time:
If strict SQL mode is enabled, an error occurs for transactional
tables and the statement is rolled back. For nontransactional tables,
an error occurs, but if this happens for the second or subsequent row
of a multiple-row statement, the preceding rows will have been
inserted.
If strict mode is not enabled, MySQL sets the column to the implicit
default value for the column data type.
So, if strict mode is not enabled for the first database, INSERT/UPDATE is allowed and storing the default value of that type (a 0 decimal)

how to make mysql database schema to be compatible with h2 database

I am currently using mysql as my database and use flyway to manage database schema. All my unit tests are running against mysql and they are running really slow with adding more unit tests. Now I want to change the database from mysql to h2 memory database in unit tests. Below is my setting for h2 db connection:
#Datasource
spring.datasource.url=jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE;DATABASE_TO_UPPER=true
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.default-transaction-isolation-level=1
When I run flywayMigrate, I got some sql errors. Below is one example, this sql is used to create a table on mysql but failed to run on h2.
CREATE TABLE `file_storage` (
`id` BIGINT(64) NOT NULL AUTO_INCREMENT,
`file_name` VARCHAR(45) NULL,
PRIMARY KEY (`id`))
DEFAULT CHARACTER SET = utf8;
below is the error I got from h2. I don't know what wrong with my sql. Is there a way for h2 to accept mysql database schema?
Execution failed for task ':dbschema:flywayMigrate'.
> Error occurred while executing flywayMigrate
Migration V2016_02_26_12_59__create_file_storage.sql failed
-----------------------------------------------------------
SQL State : 42000
Error Code : 42000
Message : Syntax error in SQL statement "CREATE TABLE ""FILE_STORAGE"" (
""ID"" BIGINT(64) NOT NULL AUTO_INCREMENT,
""FILE_NAME"" VARCHAR(45) NULL,
PRIMARY KEY (""ID""))
DEFAULT CHARACTER[*] SET = UTF8 "; SQL statement:
CREATE TABLE `file_storage` (
`id` BIGINT(64) NOT NULL AUTO_INCREMENT,
`file_name` VARCHAR(45) NULL,
PRIMARY KEY (`id`))
DEFAULT CHARACTER SET = utf8 [42000-190]
Location : db/migration/V2016_02_26_12_59__create_file_storage.sql (/Users/yzzhao/dev/cooltoo/cooltoo_backend/dbschema/build/resources/main/db/migration/V2016_02_26_12_59__create_file_storage.sql)
Line : 1
Statement : CREATE TABLE `file_storage` (
`id` BIGINT(64) NOT NULL AUTO_INCREMENT,
`file_name` VARCHAR(45) NULL,
PRIMARY KEY (`id`))
DEFAULT CHARACTER SET = utf8
Syntax error in SQL statement "CREATE TABLE ""FILE_STORAGE"" (
""ID"" BIGINT(64) NOT NULL AUTO_INCREMENT,
""FILE_NAME"" VARCHAR(45) NULL,
PRIMARY KEY (""ID""))
DEFAULT CHARACTER[*] SET = UTF8 "; SQL statement:
CREATE TABLE `file_storage` (
`id` BIGINT(64) NOT NULL AUTO_INCREMENT,
`file_name` VARCHAR(45) NULL,
PRIMARY KEY (`id`))
DEFAULT CHARACTER SET = utf8 [42000-190]
EDIT
I have hundreds of sql scripts which is running fine in mysql. So I don't want to change anything in these scripts. Is there a way to allow h2 accepts mysql script?
According to this description, you may try to use your H2 database in MySQL Compatibility Mode, by setting it in the connection string as MODE=MySQL. Here is exactly what is said about it:
To use the MySQL mode, use the database URL jdbc:h2:~/test;MODE=MySQL or the SQL statement SET MODE MySQL.
When inserting data, if a column is defined to be NOT NULL and NULL is inserted, then a 0 (or empty string, or the current timestamp for timestamp columns) value is used. Usually, this operation is not allowed and an exception is thrown.
Creating indexes in the CREATE TABLE statement is allowed using INDEX(..) or KEY(..). Example: create table test(id int primary key, name varchar(255), key idx_name(name));
Meta data calls return identifiers in lower case.
When converting a floating point number to an integer, the fractional digits are not truncated, but the value is rounded.
Concatenating NULL with another value results in the other value.
Text comparison in MySQL is case insensitive by default, while in H2 it is case sensitive (as in most other databases). H2 does support case insensitive text comparison, but it needs to be set separately, using SET IGNORECASE TRUE. This affects comparison using =, LIKE, REGEXP.
Your issue can be seen with your example
CREATE TABLE `file_storage`
(
'id` BIGINT(64) NOT NULL AUTO_INCREMENT,
`file_name` VARCHAR(45) NULL,
PRIMARY KEY (`id`)
)
DEFAULT CHARACTER SET = utf8;
The last line "DEFAULT CHARACTER SET = utf8" is setting a mySQL table option. H2 does not have such an option at either the table or schema level as it operates using Unicode at all times.
If you have a lot of SQL DDL statements that have been written over the years for MySQL you are likely to see a lot of such issues.

Unknown syntax error in MySQL statement

I am using below CREATE TABLE statement
CREATE TABLE IF NOT EXISTS users (
`uuid` varchar(36) NOT NULL,
`json` varchar(MAX) NOT NULL,
PRIMARY KEY (`uuid`)
);
However I keep getting this error.
ERROR 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
'MAX) NOT NULL,
PRIMARY KEY (uuid)
)' at line 3
Makes no sense to me.
MAX is not suported for this use, it is reserved for the MAX function. Use the equivalent number instead, check this out: Equivalent of varchar(max) in MySQL?
This will work for you. MAX is reserved keyword. Specify exact number of varchar instead of max. However, varchar(MAX) will work in SQL SERVER 2005+.
CREATE TABLE IF NOT EXISTS users (
uuid varchar(36) NOT NULL,
json varchar(21808) NOT NULL,
PRIMARY KEY (uuid)
);
FIDDLE
MAX() is a function in MySql,So if you want to declare the size to the max.please refer the below example.
CREATE TABLE IF NOT EXISTS users (
`uuid` varchar(36) NOT NULL,
`json` varchar(65535) NOT NULL,
PRIMARY KEY (`uuid`)
);
and if you calculate that 21845*3 = 65535, which wouldn't have worked anyway. Whereas 21844*3 = 65532, which does work.
mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8;
Query OK, 0 rows affected (0.32 sec)

Can't set a default value to INT(11) altering table

I am trying to alter a table and set a default value for a nullable column. But i get the following error.
Here is the command:
ALTER TABLE `questiontboard`.`questions`
CHANGE COLUMN `status` `status` (11) NULL DEFAULT 1 ;
Here is the error:
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 '(11) NULL DEFAULT 1' at line 2
SQL Statement:
ALTER TABLE `questionboard`.`questions`
CHANGE COLUMN `status` `status` (11) NULL DEFAULT 1
ERROR: Error when running failback script. Details follow.
ERROR 1050: Table 'question' already exists
What am i doing wrong?
You forgot the data type. Did you mean
ALTER TABLE `questiontboard`.`questions`
CHANGE COLUMN `status` `status` INT(11) NULL DEFAULT 1 ;
^^^
Your query should be this:
ALTER TABLE `questiontboard`.`questions`
CHANGE COLUMN `status` `status` int(11) NULL DEFAULT 1 ;
^^ here add int as you want the datatype
You are missing datatype of field in the query.
I got the same error when altering a table. I did the exact same thing you did (minus the code typo).
I got the error when altering a column from a SMALLINT to a varchar(n). It gives the "1050 Table already exists..." error. The error was confusing. Of course the table exists, that's why I'm trying to alter it!
In the end, I found out that the problem was that my new varchar(2) was not big enough to hold all the original smallint data. I had one row that had a 4 digit number, so varchar(2) wouldn't work. I changed it to use varchar(4), and it worked.
ALTER TABLE omiccom_wp.myTable
CHANGE COLUMN myColumn myColumn VARCHAR(2) NOT NULL DEFAULT '0' ;