Insert .csv file into SQL Server with BULK INSERT and reorder columns

青春壹個敷衍的年華 提交于 2019-12-13 01:42:17

问题


I make an ASP.NET application and I want to insert data into my SQL Server from a CSV file. I did it with this SQL command:

BULK
INSERT Shops
FROM 'C:\..\file.csv'
WITH
(
   FIELDTERMINATOR = ';',
   ROWTERMINATOR = '\n'
);

It pretty works but I have an id columns with AUTO INCREMENT option. I want to reorder inserted columns to SQL server increment automatiquely Id column.

How can I do that with BULK method?

(of course, I don't want to edit .csv file manualy :P )


回答1:


Like I said in my comment: You can't, bulk insert just pumps data in, you can't transform the data in any way. What you can do is bulk insert to staging table(s) and use an insert statement to do what you need to do.

You can do it like this:

-- Create staging table
SELECT   TOP 0 *
INTO     Shops_temp
FROM     Shops;


-- Bulk insert into staging
BULK INSERT Shops_temp
FROM 'C:\..\file.csv'
WITH
(
   FIELDTERMINATOR = ';',
   ROWTERMINATOR = '\n'
);


-- Insert into actual table, use SELECT for transformation, column order etc.
INSERT INTO Shops(name, etc..)
SELECT name
,      etc..
FROM   Shops_temp;


-- Cleanup
DROP TABLE Shops_temp;


来源:https://stackoverflow.com/questions/36593116/insert-csv-file-into-sql-server-with-bulk-insert-and-reorder-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!