MySQL ALTER TABLE add column: error at another column - mysql

ok, i have people table and try run sql-script with the next command:
ALTER TABLE `people`
ADD COLUMN `name_spelling`
VARCHAR(255) NULL DEFAULT NULL
AFTER `last_name`;
Then I'll get a error:
[22001][1292] Data truncation: Incorrect date value:
'0000-00-00' for column 'birth_date' at row 35
At this row birth_date is NULL, but if I try set some date like 2016-05-05 at this column and row and than set NULL back -- all works is correct at this row, but get error on some next null date.
In addition, not all null date values return error.

Maybe your MySQL has some option such as the NO_ZERO_DATE SQL mode (I think it's not the only mysql config that prevents 0000-00-00 dates). This would prevent you from using 0000-00-00 as a value. It happened to me before that I had a table already created violating that condition. It will not be editable until you change the value or disable what's preventing you to set 0 dates.
For reference :http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html

I ran into this issue once and the fix i had was to to edit mysql.cnf file
Replace : sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
with this :
sql_mode='STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
Notice i removed the No_ZEROs in that options.

Related

Set default value to all columns in a database

I am working in a PHP + MySQL application. The application is working fine for me. But when I hosted it in another server, I got a MySQL error:
Error Code: 1364. Field 'field' doesn't have a default value
I know this is a problem with the MySQL version and we should setup default values for all columns. But currently I have more than 100 tables. So I need to set default value to NULL for all columns in all tables that has no default value yet.
I can't make use of the strict mode option, because the server is a shared one. Is it possible to setup in a single step rather than setting for each and every table ? If not possible tell me the easiest way to setup it.
Any help would be greatly appreciated
For anyone else with this problem, it will take a bit of coding to perform automatically, but the following would be how you would do so:
First run the following query:
SELECT table_schema,table_name,column_name,data_type FROM information_schema.columns WHERE IS_NULLABLE='NO' AND column_default is null AND column_key=''
Next, for each row returned from the above query perform the following:
If data_type contains 'int' set default to 0
else if data_type='datetime' set default to '0000-00-00 00:00:00'
else if data_type='date' set default to '0000-00-00'
else if data_type='time' set default to '00:00:00'
else set default to ''
create and run the following query with all [[...]] variables replaced with their proper values:
ALTER TABLE `[[table_schema]]`.`[[table_name]]` ALTER COLUMN `[[column_name]]` SET DEFAULT '[[default]]'
This should replace the default values for all databases, all tables, all columns that are set to be NOT NULL and are not primary keys and have no default value set.
Another solution that i found is like:-
Get all column name put it in array...
Now push values in column array for inserting -- with ZERO value for all those arrays we do not have values.
FOR EXAMPLE:
in a table we have COLUMN
NAME LASTNAME COMPNAME PHONO EMAIL ADDRESS ALTERPERSON ALTERPHONE ALTEREMAIL
Now after migration we see the eeror
Error Code: 1364. Field 'field' doesn't have a default value
if we run a INSERT QUERY LIKE
mysqli_query($con,'insert into table
(NAME,LASTNAME,COMPNAME,PHONO,EMAIL,ADDRESS) values
(NAME,LASTNAME,COMPNAME,PHONO,EMAIL,ADDRESS)')
now it will give error...
So just turn the table
get all the column value from DB.TABLE
put it in an array or do it like one by one using while loop or for loop....
check insert values for each column
put condition if insert value is equal to ZERO or NULL then insert ZERO it will solve all issues.
WHY ZERO --
because it will work for VARCHAR,TEXT,INT,BIGINT and in many Data Types except time or date function and DATE/TIME data type got ZERO values by default...
=============================== Another option...
run a PHP code
get all TABLE NAME
then for each TABLE NAME
get all COLUMN NAME
and run this command as in function under loop
ALTER TABLE DB.TABLEnAME CHANGE columnNAME_A columnNAME_A
VARCHAR(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL
DEFAULT NULL;
=======================
And its DONE

MySQL - Adding new column with default value when condition is met

I have an existing requests table in which I want to add a new column request_type. I want to set the default value of this column to A when a certain column is not null else B. I wrote the following query which shows syntax error for MySQL version 5.7.9 -
alter table requests
add column request_type enum('A','B','C') collate utf8_unicode_ci not null default (case when userid is not null then 'A' else 'B' end)
MySQL does not support expressions for the DEFAULT.
But you can use MySQL 5.7's new feature for GENERATED columns: http://mysqlserverteam.com/generated-columns-in-mysql-5-7-5/
If you're using an older version of MySQL, you'd have to use a trigger to keep the enum column updated according to userid.

Added a Column to a table and fill it with existing column data from that table

I am updating some code removing a relationship from some terms we have with credit limits. To do this I get to update the database!
The new schema will add a column for CreditLimitCode which will be the same as the old column TermsCodeId without that columns keys. I need to leave TermsCodeId intact for the time being so a rename is not possible.
I attempted the answer for this SO question but that give me syntax errors because CreditLimitCode does not exist and I do not like the default being added.
IF COL_LENGTH('CreditApp.dbo.CreditLimit', 'CreditLimitCode') IS NULL
BEGIN
ALTER TABLE CreditApp.dbo.CreditLimit ADD CreditLimitCode VARCHAR(6) NOT NULL DEFAULT (0)
UPDATE CreditApp.dbo.CreditLimit SET CreditLimitCode = CreditTermsId WHERE CreditLimitCode = 0
PRINT 'Added CreditLimitCode to CreditLimt'
END
I am not sure a trigger for after insert here would be correct because I am altering the table not inserting rows.
exec('UPDATE CreditApp.dbo.CreditLimit
SET CreditLimitCode = CreditTermsId
WHERE CreditLimitCode = 0')
because at compilation time CreditLimitCode does not exist

Inserting datetime value into sql server table column

I'm attempting to insert a datetime('2013-08-30 19:05:00') value into a SQL server database table column(smalldatetime) and the value stays "NULL" after the insert.
I'm doing this to 6 other columns that are the exact same type. What is this only occuring on one column? I've triple checked that the names of the columns are correct. Any ideas?
Assuming the situation is as you describe
CREATE TABLE T
(
S SMALLDATETIME NULL
)
INSERT INTO T
VALUES('2013-08-30 19:05:00')
SELECT *
FROM T /*Returns NULL*/
There are only two ways I can think of that this can happen.
1) That is an ambiguous datetime format. Under the wrong session options this won't cast correctly and if you have some additional options OFF it will return NULL rather than raise an error (e.g.)
SET LANGUAGE Italian;
SET ansi_warnings OFF;
SET arithabort OFF;
INSERT INTO T
VALUES('2013-08-30 19:05:00')
SELECT *
FROM T /*NULL inserted*/
2) You may have missed the column out in an INSTEAD OF trigger, or have an AFTER trigger that actually sets the value back to NULL.

What is the best way to set up last-modified and date-record-added fields?

Hi I would like to set and forget two fields for tracking the date the record was added and also the date the record was last modified in a mySQL database.
I am using "ON UPDATE CURRENT_TIMESTAMP" and was hoping I would just change UPDATE to INSERT.
No luck however. Can anyone give me the heads up on the best way to achieve this? - preferably inside the database itself.
This assumes MySQL 5. Simply add two triggers:
create table foo (a1 INT, created timestamp, updated timestamp) engine=innodb;
DELIMITER |
CREATE TRIGGER foo_created BEFORE INSERT ON foo
FOR EACH ROW BEGIN
SET new.created := now();
SET new.updated := now();
END;
|
CREATE TRIGGER foo_updated BEFORE UPDATE ON foo
FOR EACH ROW BEGIN
SET new.updated := now();
END;
|
DELIMITER ;
insert into foo (a1) values(7);
select * from foo;
update foo set a1=9;
You basically need both columns to be setup as timestamps with default values of CURRENT_TIMESTAMP. Unfortunately, this is not allowed in MySQL:
Error Code: 1293
Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause
You can't have two timestamp columns, even though you need one to only have a default value of CURRENT_TIMESTAMP, and the other one to be UPDATE CURRENT_TIMESTAMP, this is still not allowed.
Your best bet here would be to specify as so:
CREATE TABLE `test` (
`addedDate` dateTime,
`lastModified` timestamp on update CURRENT_TIMESTAMP
)
Unfortunately, you'll have to set the 'addedDate' manually on insert using the NOW() function.
mySQL has a NOW() function you can use, see the tutorial at Tutorials Point that can help you put it in place.
You could add a DATETIME column and set it when you create the row of data. That will serve as the date the record was added.
Next, add a TIMESTAMP column:
Automatic updating of the first TIMESTAMP column in a table occurs under any of the following conditions:
You explicitly set the column to NULL.
The column is not specified explicitly in an INSERT or LOAD DATA INFILE statement.
The column is not specified explicitly in an UPDATE statement and some other column changes value. An UPDATE that sets a column to the value it does not cause the TIMESTAMP column to be updated; if you set a column to its current value, MySQL ignores the update for efficiency.
The TIMESTAMP column will take care of your record modified date.