EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
DECLARE @Command VARCHAR(1000)
SET @Command = 'dir c:\*.txt /b /s'
DECLARE @FilesInAFolder TABLE (FileNamesWithFolder VARCHAR(1000))
INSERT INTO @FilesInAFolder EXEC MASTER..xp_cmdshell @Command
; WITH TempView AS (
SELECT REVERSE(FileNamesWithFolder) ReverseFileNames FROM @FilesInAFolder
)
SELECT FileNames = REVERSE(LEFT(ReverseFileNames, CHARINDEX ('\', ReverseFileNames)-1))
FROM TempView
WHERE ReverseFileNames IS NOT NULL
EXEC sp_configure 'xp_cmdshell', 0
GO
RECONFIGURE
GO