SQL Server deletes the backup file to keep only the latest

Source: Internet
Author: User
Tags mssql


CREATE TABLE #DBNAME (ID int identity (DBNAME), nvarchar (100))
CREATE TABLE #BAK (ID int identity (), BAK nvarchar (120))
DECLARE @BakDir nvarchar (+) = ' dir/b/a:d G:\sqldata\mssql\backup\ '
DECLARE @DelStr nvarchar (2000)

INSERT into #DBNAME
EXEC xp_cmdshell @BakDir

DELETE #DBNAME WHERE DBNAME is NULL

DECLARE @count int
SELECT @count = count (1) from #DBNAME

DECLARE @ID int = 1
DECLARE @DBName nvarchar (100)
DECLARE @path nvarchar (200)

While @ID <= @count
BEGIN
SET @path = ' '
SET @DBName = NULL
TRUNCATE TABLE #BAK
SELECT @DBName = DBName from #DBNAME WHERE ID = @ID
IF @DBName is not NULL
BEGIN
SET @path = ' dir/b/o:-d G:\sqldata\mssql\backup\ ' + @DBName
DECLARE @CD nvarchar (+) = ' G:\sqldata\mssql\backup\ ' + @DBName + ' \ '
INSERT into #BAK
EXEC xp_cmdshell @path

DELETE #BAK WHERE BAK is NULL
SET @DelStr = ' DEL '
IF (SELECT COUNT (1) from #BAK) > 1
BEGIN
SELECT @DelStr + = @CD +bak+ "from #BAK WHERE ID <> 1
SET @DelStr = @DelStr + ') '
SELECT @DelStr = REPLACE (@DelStr, ') ', ')
PRINT @DelStr
EXEC xp_cmdshell @DelStr
END
END
SET @ID + = 1
END

DROP TABLE #DBNAME
DROP TABLE #BAK

SQL Server deletes the backup file to keep only the latest

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.