Translate

> > SQL server attach a series of database using query

SQL server attach a series of database using query

Posted on Wednesday, February 19, 2014 | No Comments

1 . step one
save all attach database name of you pc sql server using following command.

SELECT * FROM sys.master_files

Save the result to excel sheet.

now if you re-install your pc OS.


use the following. query for resotre all database. you may need some tuning to your database depend on the data found.




declare @dbName nvarchar(max)
declare @dbpath nvarchar(max)

declare dbc cursor for


-- Note F1 condition is used for escap some database . no need to attach those db
-- Note F2 condition is used to load only mdf file

select db_name,path from tablesm where F1>9 and F2=1


open dbc

fetch next from dbc into @dbName,@dbpath

while @@fetch_status = 0

begin

declare @logs nvarchar(max)

-- Note generating log file location from mdf file.
set @logs = substring(@dbpath,0,len(@dbpath)-3) + '.LDF'
--print @logs

declare @SQL  nvarchar(max)

set @SQL ='
CREATE DATABASE '+@dbName+'
 ON
( FILENAME = '''+@dbpath+''' ),
( FILENAME = '''+@logs+''' )
 FOR ATTACH
 '
--print @SQL
exec( @SQL)

fetch next from dbc into @dbName,@dbpath

end

close dbc
deallocate dbc

Leave a Reply

Powered by Blogger.