Monday, March 9, 2015

Simple script to dump user tbale data into copy tables

This is a quick script to dump all user table data into tables of similar schema. I had to do this once to salvage data from a corrupt database. The script uses a TRY CATCH block to continue on if in the iterative process, it encounters a table that cannot be read
 (Remove comment mark from the PRINT statement before running)

DECLARE @table VARCHAR (200)
DECLARE @sql VARCHAR (MAX)
DECLARE fetch_table CURSOR FORWARD_ONLY
FOR
SELECT [name]
FROM sys.objects
WHERE [type] = 'U'
AND is_ms_shipped = 0

 

OPEN fetch_table
FETCH NEXT FROM fetch_table INTO @table

 
nextone:

WHILE @@FETCH_STATUS = 0

BEGIN

BEGIN TRY

PRINT 'try'+' '+@table
SET @sql = 'SELECT * FROM '+@table+' INTO '+@table+'_Copy'
RAISERROR ('Test', 11, 0);
--PRINT @sql
FETCH NEXT FROM fetch_table
INTO @table

END TRY

BEGIN CATCH

PRINT 'catch '+ @table
FETCH NEXT FROM fetch_table
INTO @table
GOTO nextone

END CATCH

 

END

 

CLOSE fetch_table

DEALLOCATE fetch_table

No comments:

Post a Comment