sql-server - 从不同位置文件夹动态批量插入多个 csv 文件

标签 sql-server sql-server-2008 sql-server-2005

我在不同位置的文件夹中有多个 csv 文件。我想在 SQL Server 中动态地进行批量插入,这将在单个表中进行批量插入。 我是为单个 CSV 文件做的。有人可以帮帮我吗?

最佳答案

这里有一些可以帮助您入门的东西。您可以阅读 xp_dirtreecursors 以了解它们的工作原理。如果您的文件分布在不同的父文件夹或不同的驱动器中,您将需要一个额外的光标来获取它们...

---------------------------------------------------------------------------------------------------------------
--Set some variables
---------------------------------------------------------------------------------------------------------------

DECLARE @fileLocation VARCHAR(128) = '\\server\e$\data\'                        --location of files (parent folder)
DECLARE @sql NVARCHAR(4000)                                                     --dynamic sql variable
DECLARE @fileName VARCHAR(128)                                                  --full file name variable if you want to use this


---------------------------------------------------------------------------------------------------------------
--Get a list of all the file names in the directory
---------------------------------------------------------------------------------------------------------------

IF OBJECT_ID('tempdb..#FileNames') IS NOT NULL DROP TABLE #FileNames
CREATE TABLE #FileNames (
    id int IDENTITY(1,1)
    ,subdirectory nvarchar(512)
    ,depth int
    ,isfile bit)
INSERT #FileNames (subdirectory,depth,isfile)
EXEC xp_dirtree @fileLocation, 1, 1


--Here's all the files and folders. Note isFile field.
select * from #FileNames


---------------------------------------------------------------------------------------------------------------
--Create a cursor to fetch the file names
---------------------------------------------------------------------------------------------------------------

DECLARE c CURSOR FOR
select name from #FileNames where isfile = 1

OPEN c
FETCH NEXT FROM c INTO @fileName

---------------------------------------------------------------------------------------------------------------
--For each file, bulk insert to the proper view, update the proper table, update the log, etc...
---------------------------------------------------------------------------------------------------------------


WHILE @@FETCH_STATUS = 0
    BEGIN
        --do your bulk insert work
    FETCH NEXT FROM c INTO @fileName
    END

关于sql-server - 从不同位置文件夹动态批量插入多个 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50383902/

相关文章:

sql-server-2005 - 如果sql server 2005中的原始表不存在,则从一个表更新到另一个表

sql - 大表的自定义排序和分页

SQL Server 项目在部署后执行多个脚本

sql-server-2005 - SQL Reporting Services 2005 - 如何获取当前日期作为 ReportParameter

sql - 重命名列 SQL Server 2008

涉及 group by 和 join 的 SQL 查询

sql - 如何在 SQL Server 中使用 JOIN 执行 UPDATE 语句?

sql-server - SQL Server 中是否有元数据来确定上次更新的日期/时间?

sql - 针对不同服务器的条件 SQL

mysql - 按部门显示高于平均工资的部分