I want to execute the OpenRowSet command to pull the contents of a .txt file into 1 column. In my script, I need to loop through a collection of existing records and build a dynamic file path for each .txt file I want to import into the database, and therefore, I am using the sp_executesql procedure to execute the OpenRowSet command and output the contents of the .txt file to an output parameter.
I have tested OpenRowSet with a hard-coded file path and without passing it to the sp_executesql procedure, and I am able to retrieve the .txt file contents and insert it into my desired table in SQL. All of that is working. The issue I run into with the sp_executesql procedure is the output parameter is coming back empty. Here is a snip of the code I am running in MSSQL SMS version 15.0.18206.0 on Windows Server 2019.
DECLARE @rootDirectory VARCHAR(100)
DECLARE @filePathWithName VARCHAR(255)
DECLARE @txtFileContents VARCHAR(MAX)
DECLARE @commandText NVARCHAR(MAX)
Set @commandText = N'(Select BulkColumn FROM OPENROWSET (BULK '''+ @rootDirectory + @filePathWithName + ''', SINGLE_CLOB) Myfile)'
-- Print the command text, should contain full text file path.
print 'Command Text: ' + @commandText
-- Execute command and output text file contents.
EXEC sp_executesql @commandText,
N'@fileContentsOut VARCHAR(MAX) OUTPUT',
@fileContentsOut = @txtFileContents OUTPUT;
-- Select the file contents output.
SELECT @txtFileContents; -- <-- comes back empty???
When I execute the command above, I get a query result window that shows the contents of the .txt file in a column called "BulkColumn", but @txtFileContents parameter is empty.
Here is what the @commandText looks like before executed:
Command Text: (Select BulkColumn FROM OPENROWSET (BULK 'F:\Assets\mypath\myfile12345.TXT', SINGLE_CLOB) Myfile)
I don't understand why @txtfileContents comes back empty when I select it.