Important alert: (current site time 7/15/2013 7:47:44 PM EDT)
 

VB icon

Attaching Multiple Database Files

Email
Submitted on: 2/8/2003 4:42:37 AM
By: detanto 
Level: Intermediate
User Rating: By 2 Users
Compatibility: SQL Server 2000, SQL Server 7.0
Views: 16710
(About the author)
 
     This Stored Procedure will Attach Multiple SQL Server Database Files that have *.mdf or *.ldf extension
 
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
--**************************************
-- for :Attaching Multiple Database Files
--**************************************
detanto
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
--**************************************
-- Name: Attaching Multiple Database Files
-- Description:This Stored Procedure will Attach Multiple SQL Server Database Files that have *.mdf or *.ldf extension
-- By: detanto
--
-- Inputs:there's only one input .. that is the directory of your files 
--
-- Returns:check it in your Enterprise Manager those database will attached
--
-- Assumes:for Example your Files are in C:\SQL_Data
just type this on your query analyzer ..
(of course you have to be a member of sysadmin fixed role to do this)
exec attach_db 'c:\SQL_Data'
--
-- Side Effects:there's no side effect it will generate error if you do something wrong or there's any error on your data files
--
--This code is copyrighted and has-- limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=630&lngWId=5--for details.--**************************************

alter proc attach_db
@fileAddress varchar(1000)
as
begin
set nocount on
DECLARE 	@cmd 		sysname, 
					@var 			sysname,
					@value		varchar(100),
					@file1 		varchar(100),
					@file2			varchar(100),
					@count		numeric,
					@name		varchar(100),
					@file 			varchar(1000),
					@loop 		numeric,
					@inserted	varchar(100),
					@x2			varchar(100)
SET @var = 'dir ' + @fileAddress + '*.mdf /b'
SET @cmd = @var + ' > c:\dir_out.txt'
EXEC master..xp_cmdshell @cmd, NO_OUTPUT
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[temp_Text]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[temp_Text]
create table temp_Text
(	Files varchar(4000))
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[temp_File]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[temp_File]
create table temp_File
(	Files varchar(100))
BULK INSERT temp_Text
FROM 'c:\dir_out.txt'
WITH 
 (
 ROWTERMINATOR = ''
 )
select @file=files from temp_Text
if @@rowcount=0
	begin
		print 	'Error!!:'
		print	'Cannot Found Data File!!'
		return 0
	end
else
	begin
		set @loop=1
		while @loop>0
		begin
			set @loop	=	charindex('.MDF',upper(@file),0)
			set @inserted=left(@file,@loop)
			if len(@file)>3
				begin
					set @file=right(@file,len(@file)-@loop-3)
				end
		
			if len(@file)=0
				begin
					break
				end
			else
				begin
					if len(@inserted) = 0
						begin
							break					
						end
					else
						begin
							insert into temp_File
								values (replace(@inserted,'.',''))
						end
				end
		
		end
		
		declare cur_text cursor for
		select files from temp_File
		
		open cur_text
		fetch next from cur_text into 
		@value
		
		set @count	=	1
		while @@fetch_status=0
		begin
			
			if @count<>1
				begin
					set @file1		=	@fileAddress + right(replace(@value,' ',''),len(@value)-2) + '.MDF'
					if charindex('_Data',@value,1)<>0
						begin
							set @name	=	right(replace(@value,'_Data',''),len(@value)-7) 
							set @file2		= @fileAddress + right(replace(@value,'_Data','_Log'),len(@value)-3) + '.LDF'
						end
					else
						begin
							set @name	=	right(replace(@value,'_Data',''),len(@value)-2) 
							set @file2		=	@fileAddress + right(replace(@value,'_Data','_Log'),len(@value)-2) + '.LDF'
						end
				end
			else
				begin
					set @name	=	replace(@value,'_Data','')
					set @file1		=	@fileAddress + right(replace(@value,' ',''),len(@value)) + '.MDF'
					set @file2		=	@fileAddress + right(replace(@value,'_Data','_Log'),len(@value)) + '.LDF'
				end
			
			if len(@value)-2<>0
			begin
					if exists(select name from sysdatabases where name=@name)
						begin
							print	'Attaching Database : ' + @name + ', Failed!!'
							print 	'Error: Database ' + @name + ' exist!! '	
							print	'--------------------------------------------'
						end
					else
						begin
							exec sp_attach_db @dbname = @name,
							 	@filename1 = @file1,
								@filename2 = @file2
							if @@error=0
								print	'Attaching Database : ' + @name + ', Success !!'
						end
			end
		
			set @count=@count+1
		fetch next from cur_text into 
		@value
		end
		
		if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[temp_Text]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
		drop table [dbo].[temp_Text]
		
		if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[temp_File]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
		drop table [dbo].[temp_File]
		
		--EXEC @x2= [master].[dbo].[xp_cmdshell] 'Del c:\dir_out.txt', NO_OUTPUT
		
		close cur_text
		deallocate cur_text
	end
end


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Intermediate category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

7/27/2006 7:57:48 AMDharmendra

it is good, i m giving rating 2
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.