Here is script to attach multiple databases:
Declare @Loc varchar(1000)
Declare @SName varchar(255),@DName varchar(255),@sql VARCHAR(2000),@SQLInst varchar(255),@DB varchar(255),@Log char(1),@Data char(1)
--\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
--SET THE LOCATION OF DATABASE BACKUPS
Set @Loc='D:\iXSQl\Data\'
Declare @DBTable table (DBName varchar(255))
Set @sql='Dir /B '+@Loc
Insert into @DBtable
exec master.dbo.xp_cmdshell @sql
delete from @DBTable where RIGHT(DBName,4)<>'.mdf' or DBName is null
Create table #DBName (p sql_variant ,v sql_variant)
Create table #DBinfo (s sql_variant,f sql_variant,p sql_variant,v sql_variant)
Declare Cur Cursor
For Select DBName from @DBTable
Open Cur
Fetch Next from Cur
into @DName
While @@FETCH_STATUS =0
Begin
Print @DNAme
truncate table #DBName
truncate table #DBinfo
Set @SQL ='dbcc checkprimaryfile(''D:\iXSQl\Data\'+@DName+''',2)'
Insert into #DBName
execute (@sql)
Set @SQL ='dbcc checkprimaryfile(''D:\iXSQl\Data\'+@DName+''',3)'
Insert into #DBinfo
execute (@sql)
Select @DB=rtrim(cast([v] as varchar(255))) from #DBName Where p = 'Database name'
Set @sql = 'CREATE DATABASE '+@DB+' ON '
Select @SQL = @sql+'(FILENAME = N'''+case when rtrim(cast([v] as varchar(255))) like '%Data%'
then stuff(rtrim(cast([v] as varchar(255))),1,1,'D')
when rtrim(cast([v] as varchar(255))) like '%Log%'
then stuff(rtrim(cast([v] as varchar(255))),1,1,'F')end+''' ),' from #DBinfo
Set @sql=left (@sql,len(@sql)-1)
set @sql=@sql+' FOR ATTACH'
Print @sql
exec (@sql)
Fetch Next from Cur
into @DName
End
Close Cur
Deallocate Cur
Drop table #DBName
Drop table #DBinfo
No comments:
Post a Comment