附加目录中所有的数据库文件
DECLARE @databasedir varchar(200)
SET @databasedir = 'F:\SQLServer\Data\'
/* 目录结构 */
DECLARE @t table(id int identity(1,1),subdirectory nvarchar(255),depth int,i int)
INSERT INTO @t(subdirectory,depth,i)
EXEC master..xp_dirtree @databasedir,0,1
DELETE FROM @t WHERE subdirectory NOT LIKE '%.mdf'
DECLARE @filename nvarchar(255),@dbname nvarchar(255),@filename1 nvarchar(255),@subdirectory nvarchar(255)
DECLARE @cmd nvarchar(4000)
create table #smoPrimaryFileProp(property sql_variant NULL, value sql_variant NULL)
WHILE (SELECT COUNT(*) FROM @t) > 0
BEGIN
SELECT TOP 1 @subdirectory = subdirectory FROM @t
SELECT @fileName = @databasedir+@subdirectory;
BEGIN TRY
SET @cmd = 'dbcc checkprimaryfile (N'''+ @fileName + ''' , 2)'
TRUNCATE TABLE #smoPrimaryFileProp
insert #smoPrimaryFileProp exec (@cmd)
SELECT @dbname = CAST([value] AS nvarchar(255))
FROM #smoPrimaryFileProp WHERE [property] = 'Database name'
SELECT @filename1 = REPLACE(@fileName,'.mdf','_log.LDF');
EXEC sp_attach_db
@dbname,
@fileName,@filename1
END TRY
BEGIN CATCH
END CATCH
DELETE FROM @t WHERE subdirectory = @subdirectory
END
DROP TABLE #smoPrimaryFileProp
SET @databasedir = 'F:\SQLServer\Data\'
/* 目录结构 */
DECLARE @t table(id int identity(1,1),subdirectory nvarchar(255),depth int,i int)
INSERT INTO @t(subdirectory,depth,i)
EXEC master..xp_dirtree @databasedir,0,1
DELETE FROM @t WHERE subdirectory NOT LIKE '%.mdf'
DECLARE @filename nvarchar(255),@dbname nvarchar(255),@filename1 nvarchar(255),@subdirectory nvarchar(255)
DECLARE @cmd nvarchar(4000)
create table #smoPrimaryFileProp(property sql_variant NULL, value sql_variant NULL)
WHILE (SELECT COUNT(*) FROM @t) > 0
BEGIN
SELECT TOP 1 @subdirectory = subdirectory FROM @t
SELECT @fileName = @databasedir+@subdirectory;
BEGIN TRY
SET @cmd = 'dbcc checkprimaryfile (N'''+ @fileName + ''' , 2)'
TRUNCATE TABLE #smoPrimaryFileProp
insert #smoPrimaryFileProp exec (@cmd)
SELECT @dbname = CAST([value] AS nvarchar(255))
FROM #smoPrimaryFileProp WHERE [property] = 'Database name'
SELECT @filename1 = REPLACE(@fileName,'.mdf','_log.LDF');
EXEC sp_attach_db
@dbname,
@fileName,@filename1
END TRY
BEGIN CATCH
END CATCH
DELETE FROM @t WHERE subdirectory = @subdirectory
END
DROP TABLE #smoPrimaryFileProp