Stage it first
A staging table that looks like the target, emptied and filled by the copy on every run.
A Copy activity can write straight into a table, but then every rule about what counts as new or changed lives inside the copy's settings. Copying into a staging table first keeps the copy simple and puts those rules in SQL, where you can read, test and change them.
Two tables, one shape
The target keeps the real data and has a key. The staging table has the same columns and no key: it holds whatever the last copy brought, duplicates and all.
CREATE SCHEMA stg;
GO
CREATE TABLE dbo.Customer (
CustomerID int NOT NULL PRIMARY KEY,
FirstName nvarchar(50) NOT NULL,
LastName nvarchar(50) NOT NULL,
EmailAddress nvarchar(50) NULL,
CompanyName nvarchar(128) NULL,
ModifiedDate datetime2 NOT NULL
);
CREATE TABLE stg.Customer (
CustomerID int NULL,
FirstName nvarchar(50) NULL,
LastName nvarchar(50) NULL,
EmailAddress nvarchar(50) NULL,
CompanyName nvarchar(128) NULL,
ModifiedDate datetime2 NULL
);Every staging column allows empty values on purpose. A bad row should arrive and be dealt with in the merge, not stop the copy halfway.
The copy
In Data Factory, make a dataset for stg.Customer on the Azure SQL Database linked service. Then add a Copy activity to a new pipeline:
- Source: the Customer files in the lake, for example the Parquet folder the first course wrote.
- Sink: the
stg.Customerdataset, with Write behavior set to Insert. - Pre-copy script:
TRUNCATE TABLE stg.Customer;
The pre-copy script runs before the rows are written, so staging only ever holds this run's rows. Name the activity Copy customers; the next lessons refer to it by that name.
Map the columns
Open the Mapping tab and press Import schemas. The names match, so each column maps to itself. Check the types: a date read as text from a CSV file must land as datetime2, or the copy will fail on the first row it cannot convert.
Try it
Run the pipeline in debug mode, then look at staging:
SELECT COUNT(*) AS Rows, COUNT(DISTINCT CustomerID) AS Customers
FROM stg.Customer;If the two numbers differ, the source sent some customers twice. That is normal, and the merge in the next lesson keeps only the newest of each.