CREATE TABLE #DBNAME(ID int identity(1,1),dbname nvarchar(100))
CREATE TABLE #BAK(ID int identity(1,1),bak nvarchar(120))
DECLARE @BakDir nvarchar(100) = ‘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(100)=‘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