SQL Server xp_cmdshell

后端 未结 4 1501
慢半拍i
慢半拍i 2021-01-26 04:33

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         


        
4条回答
  •  Happy的楠姐
    2021-01-26 04:51

    Three options, depending on your environment and needs:

    1. If you're using SQL2005 or 2008, you can almost certainly write a CLR stored procedure to do this job. If you haven't done it before, it's probably more work than you're looking to do, but since I already have a project I could add this to, it's probably what I would do if I really needed SQL to be able to read from a directory.
    2. As Sam suggests, if you have access to the source of the backups, you can query the tables in the MSDB database. My suggestion might be to query msdb.dbo.backupmediafamily.physical_device_name to get a list of files that might be in available to you, then test if they exist by using: 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.
    3. If your environment makes it possible, a quick script running in Windows, outside of SQL Server, might be your best bet. You can set it up as a scheduled task if you need to. You could, for example, have it run every 15 minutes, check if a file has appeared since the last time the script ran, and insert any files into a table in SQL Server. I've done similar-enough tasks in Perl, Ruby, and VBScript. It could probably be done with a batch file, too. Again, I don't know your exact needs or skillset, but if I just needed to get this done, and didn't 100% need it to run from within SQL Server, I'd probably just write a script.

提交回复
热议问题