mysql procedure, loop tables, set default value - mysql

I have created a small stored procedure to set some defaults before inserting data (I use PhpMyAdmin) in some tables
BEGIN
ALTER TABLE capacitors MODIFY COLUMN `Part Type` VARCHAR(50) NULL DEFAULT 'Ceramic Multilayer MLCC';
ALTER TABLE capacitors MODIFY COLUMN `Package` VARCHAR(50) NULL DEFAULT '0603';
END
How can I create a procedure to make defaults in many tables for 'Distributor' and 'Distributor Currency' fields?
Pseudo:
FOR EACH table in database
IF field 'Distributor' exists -> set default to 'Mouser'
IF filed 'Distributor Currency' exists -> set default to 'USD'

Related

modify enum values in migrations scripts

Is there a correct and safe way to modify enum column type values? Add new or remove old.
E.g.: I have ENUM ("apple", "banana")
I have 2 tasks that need to add value to the ENUM. 1 needs to add orange and second needs to add peach.
If I get migrations scripts, I will have:
ALTER TABLE example MODIFY COLUMN fruit ENUM("apple", "banana", "orange) NOT NULL
ALTER TABLE example MODIFY COLUMN fruit ENUM("apple", "banana", "peach) NOT NULL
I will end up only with values from the last executed SQL. Is there a way to just add value to existing values?
You can use the show or description command.
show create table dl_stats
produces this on my system if I use print_r to show the row fetched from the database.
Array
(
[Table] => dl_stats
[Create Table] => CREATE TABLE `dl_stats` (
`Ref` bigint(20) NOT NULL AUTO_INCREMENT,
`Area` varchar(10) NOT NULL,
`Name` varchar(80) NOT NULL,
`WIN` bigint(20) NOT NULL DEFAULT 0,
`AND` bigint(20) NOT NULL DEFAULT 0,
`LNX` bigint(20) NOT NULL DEFAULT 0,
`IOS` bigint(20) NOT NULL DEFAULT 0,
`MOS` bigint(20) NOT NULL DEFAULT 0,
`MSC` bigint(20) NOT NULL DEFAULT 0,
PRIMARY KEY (`Ref`),
UNIQUE KEY `By_Name` (`Area`,`Name`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4
)
Once you have this in a variable in your language, you can parse it.
13.7.7.10 SHOW CREATE TABLE Statement
SHOW CREATE TABLE tbl_name
Shows the CREATE TABLE statement that creates the named table. To use this
statement, you must have some privilege for the table. This statement
also works with views.
From dev.mysql.com
More examples are at tutorialspoint.com
EDIT
If you want it all sql then you need to write a procedure to do it which you call from your script. This can fetch the enum value from the information_schema.
I added a column test just for testing type enum with values 'a','b','c','d' to one of my tables.
Here's a function to demo the concept. To check what is returned by the select statement. Replace the TABLE_SCHEMA, TABLE_NAME and COLUMN_NAME values to suit.
CREATE DEFINER=`root`#`localhost`
FUNCTION `Get_Def`(`New_Value` VARCHAR(40)) RETURNS LONGTEXT
CHARSET utf8mb4 NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER
return (select COLUMN_TYPE
from information_schema.`COLUMNS`
where TABLE_SCHEMA = 'aklcity_directory'
and TABLE_NAME = 'entries'
and COLUMN_NAME = 'Test')
This returns
enum('a','b','c','d')
In your procedure you can get this value as a string (more accurately longtext). You can check if the new value exists. If not, you can add it in.
To add the value 'e' to it requires
ALTER TABLE `entries` CHANGE `Test` `Test`
ENUM('a','b','c','d','e')
CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL;
Please alter to suit.

Change the field with UUID_Short failed?

I'm trying to alter current id field in organization table to UUID_SHORT but failed?
ALTER TABLE `organization` CHANGE `id` `id` BIGINT(16) UNSIGNED
NOT NULL DEFAULT uuid_short();
I don't see any error message?!
I don't think you can set the default value for id like this
Rather you can create a trigger to do this:
CREATE TRIGGER before_insert_organization
BEFORE INSERT ON organization
FOR EACH ROW
SET new.id = uuid_short();

mysql, Create Column with a default value

I've a table item that has some columns that are nullable.
To one of them type, I'd like to automatically insert a default value (instead of a NULL) whenever a new record in inserted in the table and do not specify a value for that column.
Can it be done without affecting the existing data?
The type column is a varchar.
I can update the current nulls.
You can try to ALTER column set a default value.
ALTER TABLE `T` MODIFY `type` varchar(50) DEFAULT 'default';
then insert by DEFAULT keyword:
INSERT INTO T (type) VALUES (DEFAULT);
Results:
This query will work for you.
For update table.
ALTER TABLE `column_name` CHANGE `tab` `my_id` INT(11) NOT NULL DEFAULT '0';
For insert table
CREATE TABLE `db_name`.`Tbale_name` ( `demo` INT NOT NULL DEFAULT '0');

MariaDB/MySql: Setting CURRENT_TIMESTAMP on CREATE and changing noting on UPDATE

I have not used MySQL in a few years and when I created a new table it did something I was not expecting. I am using MariaDB v5.5.60-MariaDB
I need to create a table that has both a created column and an updated column.
I need the created column to only be set to CURRENT_TIMESTAMP when the row is created and then never change unless I change it explicitly.
I need the updated column to be set to CURRENT_TIMESTAMP both when the row is created and when the row is changed.
If I do the following:
CREATE TABLE user_prefs (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE,
user VARCHAR(255) NOT NULL,
provider VARCHAR(255) NOT NULL,
pref VARCHAR(128) NOT NULL,
jsondata LONGTEXT,
created timestamp NOT NULL,
modified timestamp NOT NULL,
PRIMARY KEY (id),
UNIQUE INDEX id_UNIQUE (id ASC));
Then the created column is set to:
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
and the modified column is set to:
DEFAULT '0000-00-00 00:00:00'
If I try this:
CREATE TABLE user_prefs (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE,
user VARCHAR(255) NOT NULL,
provider VARCHAR(255) NOT NULL,
pref VARCHAR(128) NOT NULL,
jsondata LONGTEXT,
created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
modified timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE INDEX id_UNIQUE (id ASC));
Then I get the error **Error Code: 1293. Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause
**
So is there a way to automate setting both created and modified on creation of a row and then to change modified every time the row is change?
Thanks in advance.
A table might have automatic initialization of date in only one column in old versions of MySQL. But its behavior fixed in version 5.6.5.
It means you have several ways to avoid this error:
1.You can upgrade your MySQL to the latest version;
Advantages:
native clear implementation of modification dates management in a database side
there aren't excess triggers
Вrawback:
if the current version of MySQL is used in exists projects then upgrading might make some problems.
2.You can create triggers for updating and the creation of a record, as #Simonare said
Advantages:
implementation of modification dates management in a database side
Вrawback:
there are many excess triggers. You'll create two triggers for each table. It means you'll create N*2 triggers for N tables.
3.You can set default value of created column to 0000-00-00 00:00:00 and set default value of updated column to CURRENT_TIMESTAMP(). In this case date of updating will be generated automatically. Also if you write null to created column MySQL will generate current date automatically and set it to the column. For example:
CREATE TABLE example_table (
created TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
updated_at TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP
);
If you execute the following query:
INSERT INTO example_table (created) VALUES (null);
created column will have current date value. MySQL will fill it automatically.
Advantages:
there aren't excess triggers
Вrawback:
implementation of modification dates management in a database side and client application side
4.You can use automatic initialization of date in updated column and use trigger to fill created column. For example:
CREATE TABLE example_table (
created TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
updated_at TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP
);
DELIMITER //
CREATE TRIGGER example_table_set_created_date
BEFORE INSERT
ON example_table FOR EACH ROW
BEGIN
SET NEW.created = CURRENT_TIMESTAMP();
END; //
DELIMITER;
Advantages:
implementation of modification dates management in a database side
Вrawback:
there are many excess triggers. You'll create N triggers for N tables.
you can create trigger for this
DELIMITER //
CREATE TRIGGER user_prefs_before_insert
BEFORE INSERT
ON user_prefs FOR EACH ROW
BEGIN
SET NEW.updated = new.created;
END; //
DELIMITER ;
then another trigger for update
DELIMITER //
CREATE TRIGGER user_prefs_before_update
BEFORE UPDATE
ON user_prefs FOR EACH ROW
BEGIN
SET NEW.updated = CURRENT_TIMESTAMP();
END; //
DELIMITER ;

create a column with default value as null in mysql database

I want to create a column with default value as null and when any operation is performed it should change to 0. How do i do this in mysql database?
Here example how to add colum in existing table with default value
ALTER TABLE `test1` ADD `no` INT NULL DEFAULT NULL ;
When you call function then you have to write following query
UPDATE test1 SET `no` = '0' WHERE `test1`.`id` =your_id;
CREATE TABLE test
(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
test_id INT,
cost FLOAT(5,2) DEFAULT NULL,
);
each time when you do some operation on that you need to update it as #Sadikhasan
or write a trigger that will update it to zero automatically.
if the operation you want to perform is read then write trigger on ON SELECT
if the operation you want to perform is update then write trigger on ON UPDATE
like wise for others.