Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 大容量插入文件夹中的多个文件_Sql Server_Bulkinsert - Fatal编程技术网

Sql server 大容量插入文件夹中的多个文件

Sql server 大容量插入文件夹中的多个文件,sql-server,bulkinsert,Sql Server,Bulkinsert,我想用sql server读取xml文件。我将在下面展示我是如何做到这一点的 DECLARE @testxml TABLE (IntCol int, XmlCol xml); INSERT INTO @testxml(XmlCol) SELECT * FROM OPENROWSET( BULK 'C:\XMLs\32056963_0001515351.xml', SINGLE_BLOB) AS x; SELECT * FROM @testxml 一

我想用sql server读取xml文件。我将在下面展示我是如何做到这一点的

DECLARE @testxml TABLE (IntCol int, XmlCol xml);
    INSERT INTO @testxml(XmlCol)
    SELECT * FROM OPENROWSET(
       BULK 'C:\XMLs\32056963_0001515351.xml',
       SINGLE_BLOB) AS x;

SELECT * FROM @testxml
一切都好。但我需要读取文件夹中的许多文件,因此我使用:

EXEC master.sys.xp_dirtree 'C:\XMLs\',0,1;

但是,如何进行动态大容量插入以将文件夹中的所有xml文件插入到@testxml?

我不知道是否有某种方法可以一次性对所有文件进行大容量插入。我建议使用动态查询对每个文件执行导入查询。但是,为了能够从主查询中获取数据,应该将数据插入临时表中,因为表变量的作用域将限于动态查询

-- Get the file names
CREATE TABLE #files (
    subdirectory NVARCHAR(255),
    depth INT,
    file BIT
)

INSERT INTO #files
EXEC master.sys.xp_dirtree 'C:\XMLs\',0,1;

-- Iterate through the XML files
DECLARE @filesCursor CURSOR;
SET @filesCursor = CURSOR FOR
SELECT subdirectory
FROM #files
WHERE file=1 AND LEN(subdirectory)>4 AND LOWER(RIGHT(subdirectory,4))='.xml'

DECLARE @fileName NVARCHAR(255), @query NVARCHAR(MAX);

FETCH NEXT FROM @filesCursor INTO @fileName;

-- Temporary table to store the data
CREATE TABLE #testxml (IntCol int, XmlCol xml);

WHILE @@fetch_status = 0
    BEGIN
        -- Build and execute the query for each file
        SET @query = 'INSERT INTO #testxml(XmlCol) SELECT * FROM OPENROWSET(BULK ''C:\XMLs\' + @fileName + ''',SINGLE_BLOB) AS x';
        EXECUTE sp_executesql @query;

        FETCH NEXT FROM @filesCursor INTO @fileName;
    END

-- Closing and deallocating cursor
CLOSE @filesCursor;

DEALLOCATE @filesCursor;

-- Get the data from the temp table into your table variable.
-- If it is not necessary to use a table variable, you could read
-- the data directly from the temp table
DECLARE @testxml TABLE (IntCol int, XmlCol xml);

INSERT INTO @testxml
SELECT * FROM #testxml;

-- Deleting temp tables, as they won't be used anymore
DROP TABLE #testxml;

DROP TABLE #files;

使用临时表而不是表变量。在调用动态SQL之前,您只需创建#temp表。为什么我要使用临时表而不是表变量?因为临时表可以被下级执行上下文(如动态SQL)看到和使用,但表变量不能。我不喜欢游标,但根据您的回答,我对standar查询也会这样做。