It can be done but it's a vile hack, so brace yersels...
Set up a demo source table with three indexes and our empty copy table
create table fred
(
a varchar(10),
b varchar(10)
)
go
create unique index ix_fred_a on fred(a)
go
create index ix_fred_b on fred(b)
go
create index ix_fred_ab on fred(a,b)
go
select * into jim from fred where 1 = 0
We stuff the op from 'sp_helpindex fred' into a temp. table and use that to get the key names for each index.
create table #indexes
(
index_name varchar(255),
index_description varchar(255),
index_keys varchar(255)
)
insert into #indexes exec sp_helpIndex fred
delete from #indexes where index_description like '%primary key%'
Now we use a cursor to work through all the indexes for fred building a bit of dynamic SQL to create the indexes on jim.
declare @tableName varchar(50)
set @tableName = 'jim'
declare @indexName varchar(50)
declare @description varchar(255)
declare @keys varchar(255)
declare getIndex cursor
for select index_description, index_keys from #indexes
open getIndex
fetch next from getIndex into @description, @keys
while @@fetch_status = 0
begin
declare @unique varchar(20)
declare @buildIx varchar(500)
set @indexName = rtrim('IX_' + replace(cast(newid() as varchar(40)),'-',''))
set @unique = ''
if @description like '% unique %'
begin
set @unique = ' unique '
end
set @buildIx = 'create ' + @unique + 'index ' + @indexName +
' on ' + @tableName + '(' + @keys +')'
print @buildIX
exec(@buildIX)
fetch next from getIndex into @description, @keys
end
close getIndex
deallocate getIndex
If it works you should see something like the following...
create unique index IX_6A8931B2364340FCB378D9EE768C56CC on jim(a)
create index IX_4A471647B31E4499AE9C13179C511EBC on jim(a, b)
create index IX_714ED1CF6FBF4CF388B4E904E8C2E665 on jim(b)
Finally just check that we've got what we hoped for.
sp_help jim