How to change backup location dynamically in sql s

2019-09-05 15:11发布

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条回答
Animai°情兽
2楼-- · 2019-09-05 15:57

The below code worked for me.

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
查看更多
登录 后发表回答