【发布时间】:2020-10-26 21:10:34
【问题描述】:
我想执行 OpenRowSet 命令将 .txt 文件的内容拉入 1 列。在我的脚本中,我需要遍历现有记录的集合并为要导入数据库的每个 .txt 文件构建一个动态文件路径,因此,我使用 sp_executesql 过程来执行 OpenRowSet 命令并输出.txt 文件的内容到输出参数。
我已经使用硬编码文件路径测试了 OpenRowSet,并且没有将其传递给 sp_executesql 过程,并且我能够检索 .txt 文件内容并将其插入到我想要的 SQL 表中。所有这些都在起作用。我在 sp_executesql 过程中遇到的问题是输出参数返回为空。这是我在 Windows Server 2019 上的 MSSQL SMS 版本 15.0.18206.0 中运行的代码片段。
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???
当我执行上面的命令时,我得到一个查询结果窗口,它在名为“BulkColumn”的列中显示 .txt 文件的内容,但 @txtFileContents 参数为空。
这是@commandText 在执行前的样子:
Command Text: (Select BulkColumn FROM OPENROWSET (BULK 'F:\Assets\mypath\myfile12345.TXT', SINGLE_CLOB) Myfile)
我不明白为什么当我选择 @txtfileContents 时它返回为空。
【问题讨论】:
标签: sql-server tsql