May 8, 2009

Copy SQL Server database tables

Ever needed to copy an SQL Server database, but get only its data and leave out everything else?
Here's a T-SQL script that you can use to copy all the database's tables' data, and leave out everything else (indexes, partitions, programmability components, etc...)
The script will go through all tables in the 'dbo' schema of the source database (named 'sourceDatabase' in this example), create a copy of the table in the 'dbo' schema of the destination database (named 'targetDatabase') and insert all data from the source table in the destination table (by using a SELECT INTO).

Here's the code:

DECLARE @tableName varchar(300)
DECLARE @sqlStmt nvarchar(300)

DECLARE curTables CURSOR LOCAL FOR
SELECT table_name FROM sourceDatabase.INFORMATION_SCHEMA.tables


OPEN curTables

FETCH NEXT FROM curTables INTO @tableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sqlStmt = 'SELECT * INTO targetDatabase.dbo.' + @tableName + ' FROM sourceDatabase.dbo.' + @tableName
EXEC sp_executesql @sqlStmt

FETCH NEXT FROM curTables INTO @tableName
END

CLOSE curTables
DEALLOCATE curTables