Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding column to all tables in a mysql database (unknown table names)

I need to add a primary key to a set of tables in a given database. I do not know how many tables there will be or what their specific names are. They will all be of the for datatable_##, where ## will vary based everywhere my script will be run.

To add the primary key, I am using this query:

alter table datatable_??
add column ID int auto_increment not null first,
add primary key (ID);

So, I need this to run on every table in the database. It seems like I can do this in a PHP script or something, but is their a simpler way to do this just in sql script?

like image 534
PFranchise Avatar asked Apr 18 '11 17:04

PFranchise


People also ask

How can I get column names from all tables in MySQL?

How to list all tables that contain a specific column name in MySQL? You want to look for tables using the name of columns in them. SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA. COLUMNS WHERE COLUMN_NAME IN('column1', 'column2') AND TABLE_SCHEMA = 'schema_name';

How do I add one column to all tables in SQL?

SELECT 'ALTER TABLE ' + QUOTENAME(ss.name) + '.

What can you do to get a list of names of all the tables in the database?

The easiest way to find all tables in SQL is to query the INFORMATION_SCHEMA views. You do this by specifying the information schema, then the “tables” view. Here's an example. SELECT table_name, table_schema, table_type FROM information_schema.

How do I add multiple columns to an existing table in MySQL?

In MySQL, to add a new column to an existing table, the ALTER TABLE syntax would look like this: ALTER TABLE table_name ADD COLUMN column_name column_definition; Let's try adding multiple columns in one command.


2 Answers

select concat('alter table ',table_name,' add column ID int auto_increment not null primary key first;')
from information_schema.tables
where table_schema = 'db_name' and table_type = 'base table';

Once you have the output, copy and paste and run them all.

like image 167
Nicola Cossu Avatar answered Oct 23 '22 05:10

Nicola Cossu


If you want to fully script this, you can do something like this:

SELECT CONCAT('ALTER TABLE ',
table_schema,
'.',
table_name,
' ADD COLUMN id INT AUTO_INCREMENT NOT NULL PRIMARY KEY FIRST;') AS ddl
INTO OUTFILE '/tmp/alter_table.sql'
FROM information_schema.tables
WHERE table_schema = 'db_name' 
AND table_type = 'base table';

\. /tmp/alter_table.sql
like image 34
Ike Walker Avatar answered Oct 23 '22 07:10

Ike Walker