问题
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