How to change backup location dynamically in sql server

时间:2016-10-19 13:42:12

标签: sql-server-2008 tsql

Requirement : Due to some space issue our scheduled jobs are failing so to avoid this I have developed if FreeSpace is >50 GB then backup to F drive , If FreeSpace is < 50 then backup to G drive .. it has to check the all the drives and change the path automatically. Some how the below code is not working.Help on this highly appriciated.

create table #Space(Drive varchar(4),SpaceAvailable varchar(15))
insert into #Space(Drive,SpaceAvailable)
exec xp_fixeddrives 

Alter table #Space add FinalSpace as spaceavailable/1024
select * from #Space

Declare @FreeSpace varchar(10)
select @FreeSpace=(select top 1 FinalSpace  from #Space)
print @FreeSpace
if (@FreeSpace <50)
begin
backup database PerfDB to disk='G:\PerfDB.bak'
end
if (@FreeSpace >50 )
begin
backup database PerfDB to disk='F:\PerfDB.bak'
end

1 个答案:

答案 0 :(得分:0)

以下代码对我有用。

create table #Space(Drive varchar(4),SpaceAvailable varchar(15))
insert into #Space(Drive,SpaceAvailable)
exec xp_fixeddrives 

Alter table #Space add FinalSpace as spaceavailable/1024
select * from #Space

Declare @FreeSpace int=0
select @FreeSpace=51 --(select top 1 FinalSpace  from #Space)
print @FreeSpace
if (@FreeSpace between 0 and 50)
begin
print 'No Space Available'
end
if (@FreeSpace between 51 and 124  )

begin
backup database PerfDB to disk='E:\PerfDB.bak'
Print 'Loop Entered to E'
end
if (@FreeSpace  between 125 and 150  )
begin

backup database PerfDB to disk='F:\PerfDB.bak'
Print 'Loop Entered to F'
end