简体   繁体   中英

Can I shrink a SQL database log file via file path / by using it's self?

I am designing a program which shrinks database log files across a network.

The log file will not always be in the same format so I want to shrink it via the path name. To get the path names at the moment I am writing:

select top 2 physical_name as current_file_location FROM sys.master_files where physical_name like '%adventureworks%'

My script to shrink the log files are:

ALTER DATABASE adventureworks2012 SET RECOVERY SIMPLE DBCC 
SHRINKFILE ('c:\Program Files (x86)\Microsoft SQL Server\MSSQL10.50\MSSQL\DATA\adventureworks2012_log.ldf', 1) 
ALTER DATABASE adventureworks2012 SET RECOVERY FULL

This returns the error:

Could not locate file 'c:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL10.50\\MSSQL\\DATA\\AdventureWorksLog.ldf' for database 'AdventureWorks' in sys.database_files. The file either does not exist, or was dropped.

Is there a way I can make it select its self regardless of log file naming convention?

Declare @string Varchar(8000), @Strt Int ,@End Int
  select name INto #tt from  sys.databases where is_read_only=0 and state=0
  and name  NOT In ('master','model','tempdb','msdb')

  Select ROW_NUMBER()Over(Order by Name)SRNO,name INto #TTT from #tt
  Set @Strt=1
  Select @End=Max(Srno)from #ttt

  While @Strt<=@End
    Begin
        Declare @Db Varchar(255),@str varchar(Max)
        Select @Db=Name from #ttT Where Srno=@Strt
        Set @str=''
        Select  @str= 'ALTER DATABASE '''+Name+''' SET RECOVERY SIMPLE' from #tTt Where Srno=@Strt 
        --Exec (@str)
        DBCC shrinkdatabase (@Db)
        Print @Db
        Set @Strt=@Strt+1
    End

Drop Table  #tt
Drop Table  #ttT

The best solution was to grab the ID from the original select list and use that to shrink it by.

select top 2 file_id, physical_name as current_file_location FROM sys.master_files where physical_name like '%adventureworks%'

then in my second script:

DBCC SHRINKFILE (2,1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM