I need to append multiple table from multiple DB dynamically in same Azure SQL DB Server (Cloud)
I have 98 database and 352 tables in each database. All the database have same table schema. I have to append dynamically all the tables to a single destination database.
CREATE or ALTER PROCEDURE AppendTablesDynamically
AS
BEGIN
SET NOCOUNT ON;
DECLARE @TableName NVARCHAR(max),@DatabaseName NVARCHAR(max),@SQL NVARCHAR(MAX)
-- loop through all the tables in all the databases
DECLARE curTables CURSOR FOR
SELECT TABLE_NAME AS TableName,TABLE_CATALOG AS DatabaseName
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
OPEN curTables
FETCH NEXT FROM curTables INTO @TableName, @DatabaseName
WHILE @@FETCH_STATUS = 0
BEGIN
-- build the SQL statement to append the table
SET @SQL ='use' 'SELECT * into '+'merged_db.dbo.new_' +@TableName+ ' FROM '+ @TableName
-- execute the SQL statement
EXEC sp_executesql @SQL
FETCH NEXT FROM curTables INTO @TableName, @DatabaseName
END
CLOSE curTables
DEALLOCATE curTables
END
EXEC AppendTablesDynamically
Read more here: Source link
