Skip to content

Instantly share code, notes, and snippets.

@Garren
Created February 13, 2013 21:05
Show Gist options
  • Save Garren/4948246 to your computer and use it in GitHub Desktop.
Save Garren/4948246 to your computer and use it in GitHub Desktop.
Re-create ID field with identity
-- http://decipherinfosys.wordpress.com/2008/03/21/getting-the-list-of-columns-for-a-table/
exec sp_msforeachtable '
if objectproperty(object_id(''?''), ''TableHasIdentity'') = 0 and exists (select * from information_schema.columns where table_name = object_name(object_id(''?'')) group by table_schema, table_name having count(column_name) > 1)
begin
declare @tableName varchar(64)
select @tableName = object_name(object_id(''?''))
declare @cols varchar(4096)
set @cols = (SELECT TOP 1
STUFF((SELECT '', '' + T2.COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS AS T2 WHERE T2.TABLE_NAME = T1.TABLE_NAME FOR XML PATH ('''')), 1, 2,'''') AS COL_NAMES
FROM INFORMATION_SCHEMA.COLUMNS AS T1
WHERE T1.TABLE_NAME = @tableName
ORDER BY T1.ORDINAL_POSITION)
print ''select * into #'' + @tableName + '' from ?'';
print ''alter table #'' + @tableName + '' add new_ID int'';
print ''update #'' + @tableName + '' set new_ID = ID'';
print ''alter table #'' + @tableName + '' drop column ID'';
print ''alter table #'' + @tableName + '' add ID int'';
print ''update #'' + @tableName + '' set ID = new_ID'';
print ''alter table #'' + @tableName + '' drop column new_ID'';
print ''truncate table ?'';
print ''go'';
print ''alter table ? drop column ID'';
print ''alter table ? add ID int not null identity(1,1)'';
print ''go'';
print ''set identity_insert ? on'';
print ''insert into ? ('' + @cols + '') select '' + @cols + '' from #'' + @tableName + '''';
print ''set identity_insert ? off'';
print ''drop table #'' + @tableName + '''';
print ''go'';
end'
go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment