0
如何將變量傳遞給批量openrowset
命令?如何在Bulk openrowset語法中傳遞變量?
SELECT *
FROM OPENROWSET(BULK @filename, SINGLE_BLOB) AS x;
我需要動態地將文件路徑傳遞給openrowset
命令。
如何將變量傳遞給批量openrowset
命令?如何在Bulk openrowset語法中傳遞變量?
SELECT *
FROM OPENROWSET(BULK @filename, SINGLE_BLOB) AS x;
我需要動態地將文件路徑傳遞給openrowset
命令。
我不認爲你可以。我相信你必須使用動態SQL,如下面的例子:
DECLARE @FileNameWithPath VARCHAR(max)
DECLARE @FileText VARCHAR(max)
DECLARE @FileId INTEGER
DECLARE @DynamicSQLMask AS NVARCHAR(max);
DECLARE @DynamicSQL AS NVARCHAR(max);
DECLARE @dynamicparamdec AS NVARCHAR(max);
--This is a string we'll use for our SQL Command.
-- The ''##FileAndPath##'' is a target string we will replace as we loop
-- over the file.
SET @DynamicSQLMask = ' SELECT @output = BulkColumn
FROM OPENROWSET(BULK ''##FileAndPath##'', SINGLE_BLOB) AS x'
DECLARE #MyCursor CURSOR FAST_FORWARD
FOR
SELECT x.FileId
FROM Files x
OPEN #MyCursor
FETCH #MyCursor
INTO @FileId
WHILE @@fetch_status = 0
BEGIN
BEGIN TRY
-- This is setup to read a number of files. This is where you would
-- Set the filename with path each time in the loop. For Example
-- Select @FileNameWithPath = 'C:\temp\myfile.txt'
SELECT @FileNameWithPath = FT.[DataFilesPath] + '\' + Finfo.X12FileName
, @DoNotProcess = FInfo.X12Fields
FROM Files x
WHERE x.FileId = @FileId
-- Here we are building the SQL we're going to execute. Sticking with
-- The example, @FileNameAndPath would hold 'C:\Temp\myfile.txt'
-- So it would replace '##FileAndPath##' 'C:\Temp\Myfile.txt'.
-- At which point @DynamicSQL would hold
-- ' SELECT @output = BulkColumn
-- FROM OPENROWSET(BULK ''C:\Temp\Myfile.txt'', SINGLE_BLOB) AS x'
SELECT @DynamicSQL = replace(@DynamicSQLMask, '##FileAndPath##',
@FileNameWithPath)
-- This is where you're setting up a parameter for our dynamic SQL.
-- It is an output parameter so it would return the text it reads from
-- the file. Read up on sp_ExecuteSql and passing parameters
-- if this part is confusing.
SET @dynamicparamdec = '@output varchar(max) output'
EXECUTE sp_executesql @DynamicSQL
, @dynamicparamdec
, @FileText OUTPUT
-- Here we store the contents of the file we read into a table.
UPDATE Files
SET [FileText] = @FileText
WHERE FileId = @FileId
END TRY
BEGIN CATCH
select 'load failed code here'
END CATCH
FETCH #MyCursor
INTO @FileId
END -- End the Cursor Loop.
--Close the cursor, if it is empty then deallocate it:
IF (
SELECT CURSOR_STATUS('global', '#MyCursor')
) >= - 1
BEGIN
IF (
SELECT CURSOR_STATUS('global', '#MyCursor')
) > - 1
BEGIN
CLOSE #MyCursor
END
DEALLOCATE #MyCursor
END
謝謝,## FileAndPath ## - 這是溫度表嗎?請請求添加一些內聯代碼註釋以瞭解語法.. – goofyui
不,它只是一個字符串,我用它作爲替換函數的目標。選擇替換('你好,我的名字是## myname ##','## myname ##','傑伊'))會返回「你好,我的名字是傑伊」 –