Is there any other way to get a list of file names via T-SQL
other than
INSERT INTO @backups(filename)
EXEC master.sys.xp_cmdshell \'DIR /b c:\\som
The alternative to xp_cmdshell I came up is below:
My situation is a little unique in that I am attempting a poor man's log shipping. I have a folder (not the default SQL backup location) where transaction logs are deposited from a remote server. I am writing a c# app that loops through that directory and creates a comma delimited string of file names with paths (e.g. FooA.txn,FooB.txn,FooC.txn). I then feed this string into a stored procedure that I wrote which parses the string and inserts the file names into a temp table. Then I loop through the temp table restoring each transaction log in order.
Basically the C# app replaces xp_cmdshell and from the app I can call a stored procedure.
Three options, depending on your environment and needs:
RESTORE FILELISTONLY disk='FULL_PATH_TO_YOUR_FILE'
. This throws a non-fatal error if the file doesn't exist. You can check for an error in T-SQL by testing if @@error is non-zero. If you have access to the server that backup up the files, you can use the system tables to find the backup file(s) you prefer.
http://msdn.microsoft.com/en-us/library/ms188062.aspx
You'll be interested in the backup tables.
I do realize that this thread is 5 years old but I thought I'd post another non-xpCmdShell, non-CLR alternative. Details are in the following code and it's pretty simple stuff.
--===== Define the path and populate it.
-- This could be a parameter in a proc
DECLARE @pPath VARCHAR(512);
SELECT @pPath = 'C:\Temp';
--===== Create a table to store the directory information in
CREATE TABLE #DIR
(
RowNum INT IDENTITY(1,1),
ObjectName VARCHAR(512),
Depth TINYINT,
IsFile BIT,
Extension AS RIGHT(ObjectName,CHARINDEX('.',REVERSE(ObjectName))) PERSISTED
)
;
--===== Get the directory information and remember it
INSERT INTO #DIR
(ObjectName,Depth,IsFile)
EXEC xp_DirTree 'C:\Temp',1,1
;
--===== Now do whatever it is you need to do with it
SELECT * FROM #DIR;