Search

Tuesday, July 26, 2011

Find mdf files which are not attached in SQL Server instance

declare @datafile_path nvarchar(4000);
set @datafile_path = 'D:\Microsoft SQL Server\MSSQL.1\MSSQL\Data\'

select db_id() as database_id, db_name() as database_name, * into #dbfiles from sys.database_files;
delete from #dbfiles;

exec sp_msforeachdb 'use [?];insert into #dbfiles select db_id() as database_id, db_name() as database_name, * from sys.database_files'
delete from #dbfiles where type_desc <> 'ROWS'

create table #diroutput
(
[output] nvarchar(4000)
)

declare @cmd nvarchar(4000);
set @cmd = 'dir "' + @datafile_path + '*.mdf"';

insert into #diroutput
exec xp_cmdshell @cmd;

delete from #diroutput where isnull([output], N'') not like '%.mdf'
update #diroutput set [output] = rtrim(ltrim(substring([output], 21, 4000)))
update #diroutput set [output] = ltrim(substring([output], patindex('% %', [output]), 4000));
delete from #diroutput where output in ('distmdl.mdf', 'mssqlsystemresource.mdf');

with A as (
select
*
, substring(physical_name, patindex('%\Data\%', physical_name) + 6, 4000) as [filename]
from
#dbfiles

)
select
t2.[output]
from
#diroutput t2 left outer join A as t1 on t1.[filename] = t2.[output]
where
t1.[filename] is null

drop table #dbfiles
drop table #diroutput

No comments:

Post a Comment