Reputation: 4440
I have the following tables (simplified for question):
Data:
Id
Serialnumber
Value
AddressId (ForeignKey)
Addresses:
Id
Street
ZipCode
City
...
Now I have a csv file which contains data, unfortunately for both tables:
Serialnumber,Value,Street,ZipCode,City, ...
12345,1140,Fakestreet 3,12345,New York
5678,830,Fakestreet 87,12345,New York
Is there any way to import csv files like that to Microsoft SQL server (2008)? The server itself has to insert the address first, then use the primary key of the Addresses table as foreign key in the Data table.
Upvotes: 3
Views: 3322
Reputation: 13425
You need to import the CSV file into a staging Table like below and then process it accordingly.
IF (OBJECT_ID('StagingData') IS NULL)
CREATE TABLE StagingData
(
SerialNumber int,
Value int,
Street varchar(256),
ZipCode int,
City varchar(256)
)
TRUNCATE table StagingData
BULK
INSERT StagingData
FROM 'c:\csvtest.txt'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
Upvotes: 2
Reputation: 6255
INSTEAD
trigger that inserts into the actual destination tables rather than the dummy table. Remember that the trigger is going to receive multiple inserts in the same batch, and so it needs to handle multiple inserts. So capture the Address primary keys to a @table variable.Upvotes: 0