I need to get a result table with such fields - table_name, min_date, max_date
Here is my query that I have to execute for all tables
SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate FROM (SELECT short_date, type, value, count(*) as cnt FROM testTable GROUP BY short_date HAVING COUNT(*) > 1) as Duplicates
Then I found out how to get all the table names. I do it this way.
SELECT TABLE_NAME as name FROM `information_schema`.`TABLES` WHERE `TABLES`.`TABLE_SCHEMA` = 'test' AND `TABLES`.`TABLE_NAME` LIKE 'test%'
But I do not know how to execute it for the whole table and fill the result in a new table.
I tried to do it this way
DECLARE @DB_Name varchar(50) DECLARE @Command varchar(100); DECLARE database_cursor CURSOR FOR SELECT name FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES` WHERE `TABLES`.`TABLE_SCHEMA` = 'test' AND `TABLES`.`TABLE_NAME` LIKE 'test%') as TableNames OPEN database_cursor FETCH NEXT FROM database_cursor INTO @DB_Name WHILE @@FETCH_STATUS = 0 BEGIN SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate FROM (SELECT short_date, type, value, count(*) as cnt FROM ' + @DB_Name + ' WHERE type = ''test'' GROUP BY short_date, type, value HAVING COUNT(*) > 1) as Duplicates' EXEC sp_executesql @Command FETCH NEXT FROM database_cursor INTO @DB_Name END CLOSE database_cursor DEALLOCATE database_cursor
But I got this error
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that matches the version of your MySQL server. for the correct syntax to use next to 'DECLARE @DB_Name varchar (50) DECLARE @Command varchar (100)' on line 1
UPD
CREATE PROCEDURE GetData() BEGIN DECLARE @DB_Name varchar(50), @Command varchar(100); DECLARE database_cursor CURSOR FOR SELECT name FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES` WHERE `TABLES`.`TABLE_SCHEMA` = 'test' AND `TABLES`.`TABLE_NAME` LIKE 'test%_') as TableNames OPEN database_cursor FETCH NEXT FROM database_cursor INTO @DB_Name WHILE @@FETCH_STATUS = 0 BEGIN SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate FROM (SELECT short_date, type, value, count(*) as cnt FROM ' + @DB_Name + ' WHERE type = ''test'' GROUP BY short_date, type, value HAVING COUNT(*) > 1) as Duplicates' EXEC sp_executesql @Command FETCH NEXT FROM database_cursor INTO @DB_Name END; CLOSE database_cursor DEALLOCATE database_cursor END; CALL GetData()