I want to create a function to return a list of files in a directory so that I can call the function in a SELECT statement. Yes I could use a stored procedure, but then I would need to use a cursor.
This is what I want to do, but this gives the error
Invalid use of a side-effecting operator 'INSERT EXEC' within a function.
Code:
CREATE FUNCTION [dbo].[fnGetFilesInDirectory]
(@Path VARCHAR(512),
@FileMask VARCHAR(256))
RETURNS @Files TABLE (
FilePath VARCHAR(512)
)
AS
BEGIN
DECLARE @Cmd VARCHAR(8000)
SET @cmd = 'dir ' + quotename(@Path + @FileMask, NCHAR(34)) + ' /B'
INSERT INTO @Files (FilePath)
EXEC xp_cmdshell @cmd
RETURN
END
Funnily enough, this is valid:
INSERT INTO @Files (FilePath) SELECT 'test.txt'
and this is valid without the INSERT before it:
EXEC xp_cmdshell @cmd
But combining them is not.
Any suggestions on another approach to this.
xp_cmdshellto read the file system more than enough myself - but if you're doing this often enough and in the context that you're need it in a table-valued function, have you considered just reading the directory location as a part of procedural or SSIS job and querying your data from a user table location that this would write to?