我在一个文件夹中大约有30-40个CSV文件。例如,假设文件夹“佛罗里达”具有来自佛罗里达州不同城市的客户信息。每个CSV文件都包含一个城市的客户信息。现在,我想通过从该文件夹导入所有CSV文件在SQL Server中创建一个表,以便为佛罗里达州的所有客户创建一个表。我想知道是否有任何方式可以一次对所有CSV文件执行此操作。我正在使用SQL Server Management Studio(SSMS)。所有CSV文件都具有相同的列名。
我正在对一个CSV文件执行以下操作:
CREATE TABLE sales.cust (
Full_name VARCHAR (100) NOT NULL,
phone VARCHAR(50),
city VARCHAR (50) NOT NULL,
state VARCHAR (50) NOT NULL,
);
BULK INSERT sales.cust
FROM 'C:\Users..............\cust1.csv'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ',', --CSV field delimiter
ROWTERMINATOR = '\n', --Use to shift the control to next row
ERRORFILE = 'C:\Users\..............\cust1ErrorRows.csv',
TABLOCK
)
这里是将所有文件放入表中的一种方法---
-- from Chompy @https://bytes.com/topic/sql-server/answers/777399-bulk-insert-dynamic-errorfile-filename
-- 1.Create sql prototype of the Dynamic sql
---- with CSV field delimiter=',' and CSV shift the control to next row='\n'
DECLARE @sqlPrototype varchar(500)
SET @sqlPrototype = 'BULK INSERT sales.cust
FROM 'C:\Users..............\xxxx.csv'
WITH ( FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n',
ERRORFILE = 'C:\Users\..............\xxxx_ErrorRows.txt',
TABLOCK)'
-- from Rigel and froadie @ https://stackoverflow.com/questions/26096057/how-can-i-loop-through-all-the-files-in-a-folder-using-tsql
-- 2.Allow for SQL to use cmd shell
EXEC sp_configure 'show advanced options', 1 -- To allow advanced options to be changed.
RECONFIGURE -- To update the currently configured value for advanced options.
EXEC sp_configure 'xp_cmdshell', 1 -- To enable the feature.
RECONFIGURE -- To update the currently configured value for this feature.
-- 3.Get all FileNames into a temp table
CREATE TABLE #tmp(csvFileName VARCHAR(100));
INSERT INTO #tmp
EXEC xp_cmdshell 'dir /B "C:\Users..............\*.csv"';
-- 4.Loop through all of the files
Declare @fileName varchar(100)
While (Select Count(*) From #tmp where csvFileName is not null) > 0
Begin
Select Top 1 @fileName = csvFileName From #tmp
-- 5.Replace real filename into prototype
PRINT(@filename)
DECLARE @sqlstmt varchar(500)
Set @sqlstmt = replace(@sqlPrototype, ' “xxxx”', @filename).
-- 6.Execute the resulting sql
EXECUTE (@sqlstmt)
-- 4A.Remove FileName that was just processed
Delete from #tmp Where csvFileName = @FileName
End
仅由于工具有限而建议使用命令提示符。
我想到了您可以使用的另一种解决方案,它可以帮助您实现它,因此您只需导入一个文件。
创建表格:
CREATE TABLE sales.cust (
Full_name VARCHAR (100) NOT NULL,
phone VARCHAR(50),
city VARCHAR (50) NOT NULL,
state VARCHAR (50) NOT NULL,
);
使用命令提示符,请执行以下操作:
a。使用cd "C:\Users..............\"
b。使用以下命令将文件复制到一个巨型文件中:
copy *.csv combined.csv
[使用SSMS中的GUI导入该文件
带有标题的交易
从sales.cust中删除,其中full_name ='Full_name'和phone ='phone'
您只能这样做,因为所有列都是varchar。