MySQl Bulk Rename, Alter , Update - mysql

I have a MySQl database with more than 200 tables. I want to do following on ALL tables in this database.
Update all table name by adding a constant to the name
Add column (Alter table) to each table
Update each table to set newly added column
Can someone please suggest an efficient way of doing this
Thanks
bhim

You need to write a couple of SQL statements that will generate the rename / add column SQL statements.
Then you can run the SQL Statements.
You haven't provided table names, or schemas, etc. so I can give guidance but not exact results.
So assuming your "adding a constant to the name" is prefixing "const_" to it, you could do something like:
SELECT 'RENAME TABLE ''' || table_name || ''' TO ''const_' || table_name || ''' FROM information_schema.tables WHERE table_catalog = 'YourCatalog' and table_schema = 'YourSchema';
This would give you the rename table command as the output, which you could pick up and put in a text editor to tidy up.
You'll need to execute a few queries against INFORMATION_SCHEMA.tables to figure out the right filter to get the right criteria for the tables list.
And you can do similar for the Add column statement.
Some useful references:
Information schema: https://dev.mysql.com/doc/refman/5.7/en/tables-table.html
Rename a table: https://blog.marceloaltmann.com/en-how-to-rename-table-in-mysql-pt-como-renomear-tabelas-no-mysql/
Add a column: http://www.mysqltutorial.org/mysql-add-column/

Related

Change all columns of tables containing some characters

In MySQL, how to change all columns names of all tables to remove the string "_euro" from columns names?
I just could find a way to search tables having some columns containing "_euro" in their names:
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE "%_euro"
AND TABLE_SCHEMA='my_database'
For example, for the column named price_total_euro I want to rename it as price_total
Create a script with the following SQL:
SELECT CONCAT("ALTER TABLE ",TABLE_SCHEMA,".",TABLE_NAME," RENAME COLUMN ",COLUMN_NAME," TO ",REPLACE(COLUMN_NAME,"_euro",""),"; ")
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE "%_euro"
output will be, multiple lines which look like this:
ALTER TABLE test.t1_euro RENAME COLUMN t1_euro TO t1;
Review the script, and execute it on your database (after making a backup....)
put your select into a stored procedure and make a cursor and loop on all and do the alter operation
you can find example for a procedure here : https://stackoverflow.com/questions/15786240/mysql-create-stored-procedure-syntax-with-delimiter#:~:text=Getting%20started%20with%20stored%20procedure%20syntax%20in%20MySQL%3A,Why%20didn%27t%20this%20work%3F%20...%20More%20items...%20
if your using python with MySQL Connector you could place the column headers into a list and then run it through a for loop?
for name in table_names:
if name.endswith("_euro"):
new_name = name.replace("_euro", "")

Hidden character in SQL column

I've copied and pasted an SQL statement which simply adds a column into the table:
ALTER TABLE `users` ADD COLUMN `favourites​` TEXT;
However, where I have copied and pasted, the favourites name has some how managed to pick up a hidden character.
I have left the hidden character in the example above for you to see/or not see as it may be!
It's favourites?, with what appears to be a question mark.
THE PROBLEM: I need to delete this column and re-add it manually so that the hidden character is not present. The problem is that any SQL statement I do, it doesn't recognise the the column name favourites because of the hidden character and I don't know how to target it.
Has anyone got any idea how to get around this?
Do the same use show
SHOW COLUMNS FROM your_table;
for obtain the column name and then copy the column you need in your delete command
alter table your_table drop column your_column_copied
and the add the column with the right name
alter table your_table add column your_column
otherwise, if is impossible get the column_name, you can create a temp table without the wrong column with create/select command
create table (col1, col2, col3)
select col1,col2, col3
from you_table
then drop the original table and rename the temporary table and last add your column with right name
You could use dynamic query:
DECLARE #sql nvarchar(800)
SELECT #sql = 'ALTER TABLE users DROP COLUMN ' + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'users' and COLUMN_NAME LIKE '%favour%'
EXEC sp_executesql #sql
You can obtain the column name by querying INFORMATION_SCHEMA and prepare statement with the obtained column name. Something like this:
DECLARE #StrangeColumnName NVARCHAR(16) := ''
SELECT #StrangeColumnName := COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'users' AND COLUMN_NAME LIKE 'favourites%'
DECLARE #SqlText NVARCHAR(32) := 'ALTER TABLE status DROP COLUMN ?'
EXECUTE #SqlText USING #StrangeColumnName
Maybe open the information schema of the table and copy the column name from there? i don't know which Database are you using. Please update for more information.
If you have access to phpMyAdmin or, if you can create a small script to run this script:
SELECT COLUMN_NAME, FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'your_tbl_name'
OR
SHOW COLUMNS
FROM 'your_tbl_name
and copy the column name from the page.
next, you can drop that column using
alter table your_tbl_name drop column column_name;
and you already know how to add a column in mysql so, i guess that should solve your problem.
I hope you do know that you can not comment if your reputation is below 50 and if you didn't provide enough information, those who might actually have an answer for you, but have below 50 rep, will have to post it in answers. or would you like to eliminate those who are 50 rep as candidates for helping you?
In order to delete a column you can use:
alter table <tblname> drop column <colname>
and then after deleting the column you can add the column by writing below code:
ALTER TABLE users ADD COLUMN favourites​ TEXT;
Some possibilities:
Using phpmyadmin
Using a tool to talk directly to the database like navicat etc

Replace text through the entire database without assigning table or column

I've been using the following query to replace certain data:
UPDATE wx3_t1 SET umo = REPLACE(umo, 'stringbefore', 'string after');
wx3_t1 = Table
umo = Column
I am looking for a way to update across the entire database, without needing to put the table or the column into the query.
Something as simple as just REPLACE('stringbefore', 'string after')
I realize that doing it this way is really aggressive but that's fine.
You can create a simple script that query information_schema.COLUMNS to get list of all your columns by table:
select TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME from information_schema.COLUMNS;
Then you have to iterate on the result to play your UPDATE query.

Copying Tables Without Data in MySQL Retaining Auto Increment

I have ran into trouble when copying my MySQL Tables to a new one, excluding the data, using the query:
CREATE TABLE foo SELECT * FROM bar WHERE 1=0.
The tables are copied, the structure and column names are correctly inserted. But there is a problem with the auto_increment fields and the primary key fields as they are not inserted as they were on the original table. (The fields are not PKs and AI anymore) I am using MySQL 5.5 and PMA 3.5.8.2
I hope someone can help me out.
Thank you SO.
You will probably have to run 2 queries.
CREATE TABLE foo LIKE bar;
ALTER TABLE foo AUTO_INCREMENT = (SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DatabaseName' AND TABLE_NAME = 'bar');
You would have to replace DatabaseName with the name of your database. This is untested, but I think it will give you what you are looking for.
So I tried testing the above query and the ALTER TABLE statement seems to fail due to the select. There might be a better way, but the way that worked for me was to set the auto increment value to a variable and then prepare the statement and execute it.
For example you would go ahead and create your table first:
CREATE TABLE foo LIKE bar;
Then set your ALTER TABLE statement into a variable
SET #ai = CONCAT("ALTER TABLE foo AUTO_INCREMENT =", (SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'databasename' AND TABLE_NAME = 'bar'));
Finally, you would prepare and execute the statement.
PREPARE query FROM #ai;
EXECUTE query;
DEALLOCATE PREPARE query;
Other than your columns, the table structure: indexes, primary keys, triggers, etc. are not copied by this kind of statement. You either need to run a bunch of alter table statements to add your structure or you need to create the table with all the surrounding structure first, then load it with your select.

Replacement throughout the database MYSQL

I'm looking to replace all occurrences of characters in all columns of all tables in my database.
I got the name of my column like this:
select table_name, column_name from information_schema.columns;
And I would apply an UPDATE REPLACE like this:
update table_name set column_name = replace (column_name, "a", "A");
PS : The replacement of "a" to "A" is just one example, my problem is rather how to link table_name and column_name between my two queries.
I tried with subselect, like:
update (select table_name from information_schema.tables as tables) set (select column_name from columns as information_schema.columns Where table_name = tables) = replace (columns, "a", "A");
But I still get errors when I try. What is the right way to do this?
Thank you in advance.
What you need is a stored procedure that will use the information_schema to find all tables and columns within your database, and execute an update statement for all these tables.
Have a look at the following question which answers exactly what you wish to do: Find and replace in entire mysql database
It will not work like that.
You have 2 options:
1) Iterate through all tables on code side and lunch the update for each one
2) Use a stored procedure that iterate through all tables and lunch the update for each one