migrate corrupted data


In my copy/paste post I have discussed bulk insert tool. That approach is fast but sensitive to corrupted data. Here is TSQL script which allows to reload table data between  broken and new databases. It looks not elegant to load data row by row. But it allows to skip broken pages without interruption.

set nocount on
declare @id int = 0, @maxid int
select @id = min([ID]), @maxid = max([ID]) from [olddb].[dbo].[MyTable]
if exists (select top 1 1 from [newdb].[dbo].[MyTable])
select top 1 @id = max([ID]) from [newdb].[dbo].[MyTable]
while @id<=@maxid
begin
begin try
INSERT INTO [newdb].[dbo].[MyTable]([ID],[VALUE])
select p.[ID],p.[VALUE]
from [olddb].[dbo].[MyTable] p
left outer join [newdb].[dbo].[MyTable] p2 on p.[ID] = p2.[ID]
where p.[ID]=@id and p2.[ID] is null
end try
begin catch
print convert(varchar(10),@id) +’: ‘+ ERROR_MESSAGE()
end catch
begin try
select top 1 @id = [ID] from [olddb].[dbo].[MyTable] where [ID]>@id order by [ID]
end try
begin catch
set @id = @id + 1
end catch
end

Advertisements

About Andrew Butenko

https://www.mcpvirtualbusinesscard.com/VBCServer/a9939be0-be6f-4249-a775-6665eccff2e4/card https://www.microsoftvirtualacademy.com/Profile.aspx?alias=530492
This entry was posted in SQL. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s