Alter table with same name in multiple schema - mysql

I have table with same name (name-xxx) in 100 different schema in same mysql server.
I want to alter all table named xxx by using a single script (without hard coding
the schema name in the script)

You can try something like that:
DECLARE #alterQ NVARCHAR(max)
DECLARE #table_name VARCHAR(45)
DECLARE tables_curs CURSOR FOR
SELECT t.table_name
FROM INFORMATION_SCHEMA.TABLES t
WHERE t.table_name = 'xxx'
AND t.table_catalog = 'db_name'
OPEN tables_curs
FETCH tables_curs INTO #table_name
WHILE ##Fetch_Status = 0
BEGIN
SET #table_name = N'ALTER TABLE #table_name ...'
EXEC sp_executesql #alterQ
END
CLOSE tables_curs
DEALLOCATE tables_curs

Related

Mysql calling procedure failed when dynamically alter table in it

I want to alter my tables dynamically based on whether the table has specific column.
My database name is summer_cms, and there are over 50 tables in it.
What I want are below:
If a table has a column named add_time, then I would like to add a column add_user_id in it.
Similarly, I would like to add update_user_id in the table if update_time is found.
I know I should get it down in the process of creating the database schemas, but my database has been built and I have to alter it by need.
So I create a procedure to do it:
CREATE PROCEDURE ALTER_SUMMER_TABLE()
BEGIN
DECLARE tableName VARCHAR(64);
DECLARE exitence VARCHAR(64);
DECLARE ntable INT; # number of tables
DECLARE i INT; # index
SET i = 0;
# get the count of table
SELECT COUNT(DISTINCT(TABLE_NAME)) INTO ntable FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'summer_cms';
WHILE i < ntable DO
# select the specific table name into the variable of `tableName`.
SELECT TABLE_NAME INTO tableName
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'summer_cms'
AND COLUMN_NAME = 'add_time'
LIMIT 1 OFFSET i;
# alter table, but I get error in this clause.
ALTER TABLE tableName ADD COLUMN `add_user_id` INT NOT NULL DEFAULT 0 COMMENT 'add user id';
# check if the table has `update_time`
SELECT TABLE_NAME INTO exitence
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'summer_cms'
AND TABLE_NAME = tableName
AND COLUMN_NAME = 'update_time';
# add `update_user_id` if `update_time` be found.
IF exitence THEN
ALTER TABLE tableName ADD COLUMN `update_user_id` INT NOT NULL DEFAULT 0 COMMENT 'update user id';
END IF;
SET i = i + 1;
END WHILE;
END
But I got an error when I call this procedure.
Procedure execution failed
1146 - Table 'summer_cms.tableName' doesn't exist
Dose anyone could tell me what I was missing or wrong? Any help will be appreciated.
There a a few alterations you can make to your procedure to make it more streamlined as well as getting round a few problems.
First using a cursor to select the table names rather than using the two selects your using. Secondly to use a prepared statement to allow you to dynamically set the table name...
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `ALTER_SUMMER_TABLE`()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE tableName VARCHAR(64);
declare cur cursor for SELECT TABLE_NAME
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'summer_cms'
AND COLUMN_NAME = 'add_time';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
open cur;
start_loop: loop
fetch cur into tableName;
if (done = 1 )THEN
LEAVE start_loop;
END IF;
SET #sql = CONCAT('ALTER TABLE ', tableName,' ADD COLUMN `add_user_id` INT NOT NULL DEFAULT 0 ');
PREPARE stmt FROM #sql;
EXECUTE stmt;
end loop;
close cur;
END$$
DELIMITER ;
You could do a few tweaks - only fetch table names where the column doesn't already exist for example.
Here's an example of dynamic sql
drop procedure if exists alter_table;
delimiter //
CREATE DEFINER=`root`#`localhost` procedure alter_table()
begin
declare tablename varchar(20);
set tablename = 'u';
set #sqlstmt = concat('ALTER TABLE ', tableName, ' ADD COLUMN ', char(96), 'add_user_id', char(96), ' INT NOT NULL DEFAULT 0 COMMENT', char(39), 'add user id', char(39),';');
prepare stmt from #sqlstmt;
execute stmt;
deallocate prepare stmt;
end //
delimiter ;
Note I have used ascii backticks and single quotes.

mysql stored procedure to alter column type

In my MySQL setup I have about a dozen database with hundreds of tables where all id fields are defined with type varchar(20). Per database there are a few thousand of these fields. These fields need to be altered into varchar(36).
In order to make this happen I have created a stored procedure, that:
gets all appropriate schemas;
get the tables of the schemas;
loop through all the columns and when the column type = 'varchar(20) alter the column to varchar(36).
The content of the procedure is available below. But instead of altered column types I get nothing. Meaning there is something wrong. But what is it?
Can you help me out?
DELIMITER $$
DROP PROCEDURE IF EXISTS `get_database`$$
DROP PROCEDURE IF EXISTS `get_table`$$
DROP PROCEDURE IF EXISTS `get_column`$$
DROP PROCEDURE IF EXISTS `alter_column`$$
CREATE PROCEDURE get_database()
BEGIN
DECLARE db_rows INT;
DECLARE dbI INT DEFAULT 1;
DECLARE db_name VARCHAR(255);
DECLARE db_names CURSOR FOR SELECT schema_name FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME LIKE '%ofb%';
SET #enabled = TRUE;
select FOUND_ROWS() into db_rows;
open db_names;
db_loop: LOOP
if dbI > db_rows THEN
CLOSE db_names;
LEAVE db_loop;
end if;
FETCH db_names INTO db_name;
-- database found
if db_name then
call get_table(db_name);
end if;
SET #dbI = #dbI + 1;
END LOOP db_loop;
END $$
CREATE PROCEDURE get_table(db_name VARCHAR(255))
BEGIN
DECLARE tn_rows INT;
DECLARE tnI INT DEFAULT 1;
DECLARE table_name VARCHAR(255);
DECLARE table_names CURSOR FOR SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = db_name;
SET #enabled = TRUE;
SET tnI = 1;
SET #enabled = TRUE;
select FOUND_ROWS() into tn_rows;
open table_names;
table_loop: LOOP
if tnI > tn_rows THEN
CLOSE table_names;
LEAVE table_loop;
end if;
FETCH table_names INTO table_name;
-- table_name found
if table_name then
call get_column(db_name, table_name);
end if;
SET tnI = tnI + 1;
END LOOP table_loop;
END $$
CREATE PROCEDURE get_column(db_name VARCHAR(255), table_name VARCHAR(255))
BEGIN
DECLARE cn_rows INT;
DECLARE cnI INT DEFAULT 1;
DECLARE column_name VARCHAR(255);
DECLARE column_names
CURSOR FOR SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = db_name and TABLE_SCHEMA = table_name;
SET #enabled = TRUE;
SET cnI = 1;
select FOUND_ROWS() into cn_rows;
open column_names;
column_loop: LOOP
if cnI > nn_rows THEN
CLOSE column_names;
LEAVE column_loop;
end if;
FETCH column_names INTO column_name;
-- column_name found
if column_name then
call alter_column(db_name, table_name, column_name);
end if;
SET cnI = cnI + 1;
END LOOP column_loop;
END $$
CREATE PROCEDURE alter_column(db_name VARCHAR(255), table_name VARCHAR(255), column_name VARCHAR(255))
BEGIN
DECLARE dtype VARCHAR(255);
declare data_type
CURSOR FOR SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = table_name and TABLE_NAME = table_name AND COLUMN_NAME = column_name;
open data_type;
fetch data_type into dType;
if dType = 'varchar(20)' then
SET #ddl = CONCAT('alter table ', db_name, '.',table_name, ' modify column (', column_name, ' VARCHAR(36))');
PREPARE STMT FROM #ddl;
EXECUTE STMT;
end if;
END $$
DELIMITER ;
Your help is appreciated.
Best regards
I was in need of these procedures, and see some changes I made, that worked:
CREATE PROCEDURE get_database()
BEGIN
DECLARE _table_name VARCHAR(255);
DECLARE finished INTEGER DEFAULT 0;
DECLARE table_names CURSOR FOR
SELECT table_name
FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_SCHEMA like '%ofb%';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN table_names;
table_loop: LOOP
FETCH table_names INTO _table_name;
IF finished = 1 THEN
CLOSE table_names;
LEAVE table_loop;
END IF;
CALL get_column('%ofb%', _table_name);
END LOOP table_loop;
END
CREATE PROCEDURE get_column(db_name VARCHAR(255), table_name VARCHAR(255))
BEGIN
DECLARE _column_name VARCHAR(255);
DECLARE finished INTEGER DEFAULT 0;
DECLARE column_names CURSOR FOR
SELECT column_name FROM
INFORMATION_SCHEMA.COLUMNS
WHERE table_schema LIKE db_name AND
TABLE_NAME = _table_name AND
DATA_TYPE = "varchar" AND
CHARACTER_MAXIMUM_LENGTH = 20
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN column_names;
column_loop: LOOP
FETCH column_names INTO _column_name;
IF finished = 1 THEN
CLOSE column_names;
LEAVE column_loop;
END IF;
SET #ddl = CONCAT('ALTER TABLE ', db_name, '.',_table_name, ' MODIFY COLUMN ', _column_name, ' VARCHAR(36) NULL');
PREPARE STMT FROM #ddl;
EXECUTE STMT;
END LOOP column_loop;
END

Rename column for all tables in mysql database

I need to rename column for all tables in my databse.
I could get list of columns using this query:
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME= <Column Name>;
But how actually I could rename it as simple as possible and do not write
ALTER TABLE <Table Name >RENAME COLUMN <Old name> to <New Name>;
for each table.
I've tried to write a procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS renameColumn $$
CREATE PROCEDURE renameColumn(IN oldName tinytext, IN newName tinytext)
BEGIN
DECLARE #name VARCHAR(255);
DECLARE exit_loop BOOLEAN;
DECLARE tableName_cursor CURSOR FOR SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME=oldName;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET exit_loop = TRUE;
OPEN tableName_cursor;
rename_loop: LOOP
FETCH tableName_cursor #name;
ALTER TABLE #name RENAME COLUMN oldName to newName;
IF exit_loop THEN
LEAVE rename_loop;
END IF;
END LOOP rename_loop;
END $$
DELIMITER;
But I have the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#name VARCHAR(255);
DECLARE exit_loop BOOLEAN;
DECLARE ta' at line 3
Could you please help me to resolve this issue
You can try this.
SELECT CONCAT(
'ALTER TABLE ', TABLE_NAME,
' RENAME COLUMN ', COLUMN_NAME,
' NEW_', COLUMN_NAME,
';') AS rename_script
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'your_db'
Try the following solution hope it will help
DECLARE #name VARCHAR(50) -- database name
DECLARE db_cursor CURSOR FOR
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME= 'OldColumn';
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
set #name = #name + '.OldColumn'
EXEC sp_rename #name, 'NewColumn', 'COLUMN';
print(#name)
FETCH NEXT FROM db_cursor INTO #name
END
CLOSE db_cursor
DEALLOCATE db_cursor

Show table name where a value is present

Is it possible to show the name of a table in a db where a specific value is present. I have different tables and i want to show only the table names that contains a specific value in any of the fields.
This will return lots of empty result sets, but the non-empty ones correspond to table/column combinations that fit your search. It only works for text, and detects columns that contain the value (as opposed to a full column match.)
DELIMITER |
DROP PROCEDURE IF EXISTS `SearchAllTables`|
CREATE PROCEDURE `SearchAllTables` (
IN _search varchar(256)
)
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY DEFINER
BEGIN
-- declare stuff
declare _tableName varchar(64);
declare _columnName varchar(64);
declare _done tinyint(1) default 0;
-- we will examine every string column in the database
declare _columnCursor cursor for
select TABLE_NAME, COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = database()
and (DATA_TYPE like '%char%'
or DATA_TYPE like 'text');
declare CONTINUE handler for NOT FOUND
SET _done = 1;
OPEN _columnCursor;
LOOP1: LOOP
-- get the next table/column combination
FETCH _columnCursor INTO _tableName,_columnName;
IF _done = 1 THEN
CLOSE _columnCursor;
LEAVE LOOP1;
END IF;
-- query the current column to see if it holds the value
SET #query = concat(
"select '",_tableName,"' as TableName, '",
_columnName,"' as ColumnName
from ",_tableName,"
where ",_columnName," like concat('%',?,'%')
group by 1;"
);
SET #search = _search;
PREPARE _stmt FROM #query;
EXECUTE _stmt USING #search;
DEALLOCATE PREPARE _stmt;
END LOOP LOOP1;
END|
DELIMITER ;
Oh, yeah, and it's ugly... Maybe it'll help you, though!
SELECT TABLE_NAME
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'database_name'
AND COLUMN_NAME = 'column_name'

SQL Server: Can you help me with this query?

I want to run a diagnostic report on our SQL Server 2008 database server.
I am looping through all of the databases, and then for each database, I want to look at each table. But, when I go to look at each table (with tbl_cursor), it always picks up the tables in the database 'master'.
I think it's because of my tbl_cursor selection :
SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'
How do I fix this?
Here's the entire code:
SET NOCOUNT ON
DECLARE #table_count INT
DECLARE #db_cursor VARCHAR(100)
DECLARE database_cursor CURSOR FOR
SELECT name FROM sys.databases where name<>N'master'
OPEN database_cursor
FETCH NEXT FROM database_cursor INTO #db_cursor
WHILE ##Fetch_status = 0
BEGIN
PRINT #db_cursor
SET #table_count = 0
DECLARE #table_cursor VARCHAR(100)
DECLARE tbl_cursor CURSOR FOR
SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'
OPEN tbl_cursor
FETCH NEXT FROM tbl_cursor INTO #table_cursor
WHILE ##Fetch_status = 0
BEGIN
DECLARE #table_cmd NVARCHAR(255)
SET #table_cmd = N'IF NOT EXISTS( SELECT TOP(1) * FROM ' + #table_cursor + ') PRINT N'' Table ''''' + #table_cursor + ''''' is empty'' '
--PRINT #table_cmd --debug
EXEC sp_executesql #table_cmd
SET #table_count = #table_count + 1
FETCH NEXT FROM tbl_cursor INTO #table_cursor
END
CLOSE tbl_cursor
DEALLOCATE tbl_cursor
PRINT #db_cursor + N' Total Tables : ' + CAST( #table_count as varchar(2) )
PRINT N'' -- print another blank line
SET #table_count = 0
FETCH NEXT FROM database_cursor INTO #db_cursor
END
CLOSE database_cursor
DEALLOCATE database_cursor
SET NOCOUNT OFF
The problem is because you're actually always running the INFORMATION_SCHEMA.TABLES query under the master db context.
You'd need to convert the tbl_cursor block into dynamic SQL in order to fully qualify the query with the DB name.
e.g.
SELECT table_name FROM YourDatabase.INFORMATION_SCHEMA.TABLES WHERE....
is essentially what you need to be executing for that cursor.
It's easier to use table variables so you can add rows to #tablist using another dynamic SQL statement
SET NOCOUNT ON
DECLARE #table_count INT
DECLARE #dblist TABLE (DBName VARCHAR(100))
DECLARE #tablist TABLE (TableName VARCHAR(100))
DECLARE #dbname varchar(100), #tabname varchar(100)
INSERT #dblist
SELECT name FROM sys.databases where name<>N'master'
SELECT TOP 1 #dbname = DBName FROM #dblist
WHILE ##ROWCOUNT <> 0
BEGIN
INSERT #tablist (tableName)
EXEC ('SELECT table_name FROM ' + #dbname + '.information_schema.tables WHERE table_type = ''base table'' ')
SELECT TOP 1 #tabname = tableName FROM #tablist
WHILE ##ROWCOUNT <> 0
BEGIN
--do my stuff
DELETE #tablist WHERE tableName = #tabname
SELECT TOP 1 #tabname = tableName FROM #tablist
END
DELETE #dblist WHERE DBName = #dbname
SELECT TOP 1 #dbname = DBName FROM #dblist
END
You might have to create dynamic SQL. because information_schema will fetch objects only from the current active database against which you are running this query.
you can try sys.objects