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?
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';
SELECT 'ALTER TABLE ' + QUOTENAME(ss.name) + '.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With