1

I have an SQL script which I want to run on multiple databases. The script runs a couple of update and insert statements and I also want to open and parse an xml file on different paths.
The issue I have is that I know where the file I want to open is (the directory) but I don't know its name (the name is random) but the extension is always .profile (which is a xml file) and there is only one file in each directory.
I wonder how I can open a XML/profile file without knowing its exact name using MS SQL.

3 Answers 3

2

As far as I understand your question correctly:

declare @files table (ID int IDENTITY, fileName varchar(max))
insert into @files execute xp_cmdshell 'dir <yourdirectoryhere>\*.profile /b'
declare @fileName varchar(max)
select top 1 @fineName = fileName * from @files

does what you want but is based on calling xp_cmdshell and it's usually a very bad idea to use it.

Sign up to request clarification or add additional context in comments.

Comments

1

Try something along the lines of this:

DECLARE @output NVARCHAR(MAX) 

CREATE TABLE #OUTPUT 
  ( 
     OUTPUT VARCHAR(255) NULL 
  ) 

INSERT #OUTPUT 
EXEC @output = XP_CMDSHELL 
  'DIR "C:\temp\*.profile" /B ' 

SELECT * 
FROM   #OUTPUT 

DROP TABLE #OUTPUT 

Comments

-1

As explained here (and that's just one way), you can access disk contents from SQL Server, provided your permissions are working fine.

IIRC, the following options need to be enabled. However, you need them anyway to access files from SQL Server.

EXEC sp_configure 'show advanced options', 1
GO

RECONFIGURE
GO

EXEC sp_configure 'xp_cmdshell', 1
GO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.