Counter of Festivals

Ashok Blog for SQL Learners and Beginners and Experts

Monday 3 February 2014

To find out LDF or MDF file usage or not

----------------------To know MDF or  LDF file currently using or not one by one-------------------

Go
SELECT Name,physical_name,* FROM sys.database_files

But We have to run db one by one. because it gives details by current db only

------------------------To find MDF OR LDF all DB at time-------------------------------------------

DECLARE @CurrentDB sysname
DECLARE @SQL NVARCHAR(1000)
DECLARE @FileToFind NVARCHAR(260)

SET @FileToFind='master.mdf'

CREATE TABLE #TmpDBTable (
    DBName sysname,
    FileName NVARCHAR(260)
)

DECLARE ALLDBS CURSOR FOR
SELECT NAME FROM sys.databases
OPEN ALLDBS
FETCH NEXT FROM ALLDBS INTO @CurrentDB 
WHILE @@FETCH_STATUS=0
BEGIN
    SET @SQL='use ' + @CurrentDB + ';insert #TmpDBTable select '''+@CurrentDB+''',physical_name from sys.database_files where physical_name like ''%'+@FileToFind+'%'''
    EXEC sp_executesql @SQL
    FETCH NEXT FROM ALLDBS INTO @CurrentDB 
END
CLOSE ALLDBS
DEALLOCATE ALLDBS

SELECT * FROM #TmpDBTable

DROP TABLE #TmpDBTable



No comments:

Post a Comment