因此,我尝试将一堆PDF从一个文件夹读取到SQL表中,并将其保存在varbinary(max)字段中。这是我最初想的效果:
# Define function to center the text in the current line (taken from: https://stackoverflow.com/a/48622585/10516690)
function Write-HostCenter {
param($Message)
Write-Host ("{0}{1}" -f (' ' * (([Math]::Max(0, $Host.UI.RawUI.BufferSize.Width / 2) - [Math]::Floor($Message.Length / 2)))), $Message)
}
# Define Test-Connection as a string for Invoke-Expression later
[string]$TestConn = "Test-Connection -Quiet -Count 1 -ComputerName "
# Define excluded servers
$ExclusionList = @("Server1","Server2","Server3")
但这不起作用,因为它不允许我在此行中使用变量:
CREATE TABLE tempFileName(filnavn VARCHAR(100));
INSERT INTO tempFileName
EXEC xp_cmdshell 'dir /B "C:\temp\Test Folder\"';
--------
DECLARE @path VARCHAR(100) SET @path = 'C:\temp\Test Folder\'
DECLARE @pdf VARBINARY(MAX)
DECLARE @navn varchar(50)
DECLARE @fullpath nvarchar(max)
DECLARE @sql nvarchar(max)
DECLARE c CURSOR FOR
SELECT filnavn
FROM tempFileName
OPEN c
FETCH NEXT FROM c INTO @navn
WHILE(@@FETCH_STATUS = 0)
BEGIN
SET @fullpath = @path + @navn
SELECT @pdf = BulkColumn
FROM OPENROWSET(BULK @fullpath, SINGLE_BLOB) AS Document;
--print @sql
INSERT INTO pdftest VALUES(@navn, @pdf)
FETCH NEXT FROM c INTO @navn
END
CLOSE c
DEALLOCATE c
所以我很确定诀窍是将整个“ select @pdf ..”行变成一个字符串然后执行它,但是我不确定如何将输出放入表中。我已经尝试过这样的事情:
FROM OPENROWSET(BULK @fullpath, SINGLE_BLOB) AS Document;
但是此后@fil变量为空。如何最好地将这些文件放入表中?
答案 0 :(得分:1)
为什么不只在循环中跳过SELECT的变量分配,而在INSERT中使用OPENROWSET函数?总体思路:
INSERT INTO pdftest SELECT @navn, * FROM OPENROWSET(BULK, 'C:\thefile.txt', SINGLE_BLOB) AS document
当然,上面又变成了动态SQL。在这里,我可能会弄错一些单引号,但总的来说还是这样:
SET @sql =
'INSERT INTO pdftest
SELECT '' + @navn + '', *
FROM OPENROWSET(BULK, ''' + @fullpath + ''', SINGLE_BLOB) AS document
'