DEV Community

Cover image for SQL Server to Databricks With CDC: From sp_cdc_enable_db to a Unity Catalog Query
Shubham Baldava
Shubham Baldava

Posted on

SQL Server to Databricks With CDC: From sp_cdc_enable_db to a Unity Catalog Query

Copying a table from SQL Server to Databricks once is easy. Keeping that copy current is the hard part: an order flips to delivered, a customer moves city, and Databricks keeps the old value until the next full export. Deletes are worse: an incremental file load has no way to say that a row went away, so you fall back to reloading the whole table.

SQL Server ships its own change feed. Change data capture (CDC) has the SQL Server Agent read the transaction log and write every change into a change table per tracked table, such as cdc.dbo_customers_CT. The open question is what reads those tables.

Ways to move SQL Server data into Databricks

  • bcp export, then Auto Loader. The bulk copy utility writes each table to files in a bucket, and Auto Loader picks them up. Freshness is hours to daily, and a changed row means a full reload or a merge you write yourself.
  • Debezium and Kafka, read with Structured Streaming. Changes arrive within seconds. You run Kafka, Kafka Connect, the Debezium SQL Server connector and a Databricks job that keeps running, and the merge logic is yours.
  • Lakeflow Connect. Databricks' managed ingestion lists SQL Server among its CDC database connectors, reading through change tracking or CDC (checked Oct 2026). Nothing to host: it runs on Databricks compute and writes tables the pipeline manages.

This tutorial takes a fourth route. OLake Go, an open source (Apache 2.0) replication tool, drains the change tables on a schedule and commits Apache Iceberg tables straight into Unity Catalog. Databricks treats them as Unity Catalog managed Iceberg tables, and DuckDB and Spark read the same files through the same catalog.

I ran every step below on SQL Server 2022 Developer in Docker, OLake Go v1.1.0 and a Databricks workspace on Google Cloud. The timings and row counts are from that run.

What the SQL Server to Databricks pipeline looks like

  • Source: SQL Server with CDC on the shop database and on two tables, dbo.customers and dbo.orders.
  • Pipeline: OLake UI from Docker Compose. The first sync records the current log sequence number (LSN) and reads each table in parallel chunks. Every later sync reads only the change tables, starting at the saved LSN.
  • Destination: the Iceberg REST (representational state transfer) endpoint of Unity Catalog. Updates land as Iceberg v3 deletion vectors, the only row-level delete format Databricks reads under Unity Catalog.

You need: SQL Server 2016 SP1 or later on Developer, Standard or Enterprise edition, a Databricks workspace with Unity Catalog, an admin who can grant EXTERNAL USE SCHEMA, Docker, and about 40 minutes.

Step 1: Turn on CDC in SQL Server

To follow along with the same data, create these two tables in a database called shop. My run started with 8 customers and 40 orders. The change step later updates two customers by name, Liam Carter and Zara Ali, so include them or edit those lines.

CREATE TABLE dbo.customers (
  id INT IDENTITY(1,1) PRIMARY KEY,
  name NVARCHAR(100), email NVARCHAR(200), city NVARCHAR(100), tier NVARCHAR(20),
  created_at DATETIME2 DEFAULT SYSUTCDATETIME(),
  updated_at DATETIME2 DEFAULT SYSUTCDATETIME());

CREATE TABLE dbo.orders (
  id INT IDENTITY(1,1) PRIMARY KEY,
  customer_id INT REFERENCES dbo.customers(id),
  product NVARCHAR(100), amount DECIMAL(10,2), status NVARCHAR(20),
  created_at DATETIME2 DEFAULT SYSUTCDATETIME(),
  updated_at DATETIME2 DEFAULT SYSUTCDATETIME());
Enter fullscreen mode Exit fullscreen mode

Now switch on CDC for the database and both tables, and create the login OLake Go connects with:

USE shop;
EXEC sys.sp_cdc_enable_db;

EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', @source_name = N'customers', @role_name = NULL;
EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', @source_name = N'orders',    @role_name = NULL;

USE master;
CREATE LOGIN olake WITH PASSWORD = '<password>';
USE shop;
CREATE USER olake FOR LOGIN olake;
GRANT SELECT ON SCHEMA :: dbo TO olake;
GRANT SELECT ON SCHEMA :: cdc TO olake;
GRANT VIEW DATABASE STATE TO olake;

USE msdb;
CREATE USER olake FOR LOGIN olake;
GRANT SELECT ON dbo.cdc_jobs TO olake;
Enter fullscreen mode Exit fullscreen mode

Then confirm all three pieces exist:

SELECT name, is_cdc_enabled FROM sys.databases WHERE name = 'shop';   -- 1
SELECT capture_instance FROM cdc.change_tables;                        -- dbo_customers, dbo_orders
EXEC msdb.dbo.sp_help_job @job_name = N'cdc.shop_capture';             -- the Agent job exists
Enter fullscreen mode Exit fullscreen mode

What matters on a real server:

  • The Agent fills the change tables. If the SQL Server Agent is stopped, no change rows appear and SQL Server reports no error. On Amazon RDS and Azure SQL Managed Instance it runs by default.
  • Change rows expire. The cleanup job deletes them after three days by default, so a job paused longer than that needs a fresh snapshot.
  • Hosted SQL Server enables CDC with its own procedure: EXEC msdb.dbo.rds_cdc_enable_db 'shop' on Amazon RDS, EXEC msdb.dbo.gcloudsql_cdc_enable_db 'shop' on Cloud SQL. The table step is unchanged.

Step 2: Prepare Unity Catalog

Unity Catalog needs four things, once per workspace:

  1. External data access on the metastore: Catalog, the gear icon, Metastore, then External data access. Without it, the endpoint turns away every client that is not Databricks.
  2. A catalog with managed storage, backed by an external location in your cloud account.
  3. EXTERNAL USE SCHEMA on that catalog for the writing principal.
  4. A personal access token for that principal, from Settings, Developer, Access tokens.
CREATE CATALOG IF NOT EXISTS lakehouse MANAGED LOCATION '<external location URL>/lakehouse';

GRANT USE CATALOG, CREATE SCHEMA ON CATALOG lakehouse TO `olake@example.com`;
GRANT USE SCHEMA, CREATE TABLE, SELECT, MODIFY ON CATALOG lakehouse TO `olake@example.com`;
GRANT EXTERNAL USE SCHEMA ON CATALOG lakehouse TO `olake@example.com`;
Enter fullscreen mode Exit fullscreen mode

Grants on the catalog carry down to every schema OLake Go creates later. EXTERNAL USE SCHEMA is not part of ALL PRIVILEGES, and only the catalog owner can grant it (Databricks: Unity Catalog privileges). My run wrote into a catalog named datazip with a token that expired after seven days, and the snippets here use lakehouse.

Step 3: Start OLake UI and add SQL Server

curl -sSL https://raw.githubusercontent.com/datazip-inc/olake-ui/master/docker-compose-v1.yml | docker compose -f - up -d
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:8000, go to Sources and click Create Source. Pick MSSQL, name the source and keep the OLake Go version on the latest release.

Leave Enable CDC on. Manage Capture Instance lets OLake Go create a new capture instance after a schema change, and it then needs db_owner; leave it off to manage capture instances by hand. Under Connection details, my SQL Server ran in another container, so the host was host.docker.internal, with port 1433, database shop, user olake and SSL off.

OLake UI Edit source form for MSSQL with Enable CDC on, host host.docker.internal, port 1433, database shop, user olake and SSL disabled

Click Set up source. It tests the connection, then checks for CDC on the database, a capture instance per table and a readable capture job. A failed check shows the current value, the recommended one and what to run.

Step 4: Add the Unity Catalog destination

Go to Destinations, then Create Destination, then Apache Iceberg, and pick Unity as the catalog type with Personal Access Token authentication.

Field Value
REST Catalog URL https://<workspace-url>/api/2.1/unity-catalog/iceberg-rest
Unity Catalog Name lakehouse (the catalog from step 2)
Token the personal access token from step 2

OLake UI destination form for an Apache Iceberg destination with the Unity catalog type and the personal access token fields

Click Create. OLake Go calls the Unity Catalog endpoint with the token and saves the destination, so external data access left off, a missing EXTERNAL USE SCHEMA or a mistyped catalog name fails right here.

Step 5: Create the job and run the first sync

Open Jobs and click Create Job. I named mine sql_server_to_databricks, picked the source and the destination, and gave it a schedule. The schedule only decides how often the change tables are drained; it never triggers another full copy.

Under Advanced Settings, set Target Query Engines to Databricks, plus DuckDB and Apache Spark if they will read the tables. It decides the delete format: with Databricks listed, OLake Go resolves deletion vectors on Iceberg v3 tables, and there is nothing to pick by hand.

Click Next. On the Streams page, tick customers and orders, set each to Full Refresh + CDC with ingestion mode Upsert, and leave the Upsert Type at the Deletion Vector that OLake Go resolved. Discovery also lists systranschemas, a table SQL Server added when CDC was enabled; leave it unticked.

OLake UI Streams Selection page with dbo customers and orders selected, systranschemas unticked, Full Refresh + CDC, Upsert and Deletion Vector on Iceberg format version V3

Click Create Job, open the job menu and choose Sync Now. My first run copied 8 customers and 40 orders, 48 records and 3.05 KB, in 27 seconds with container start included.

The Unity Catalog schema is named after the job, the source database and the schema, so this job produced sql_server_to_databricks_shop_dbo. The Iceberg DB field at the top of the Streams page renames it before the first sync.

Step 6: Query the tables in Databricks

There is no external table to define and nothing to refresh. Open the SQL editor on any SQL warehouse; my checks ran on a 2X-Small serverless SQL warehouse.

SHOW TABLES IN lakehouse.sql_server_to_databricks_shop_dbo;

SELECT id, name, city, tier
FROM lakehouse.sql_server_to_databricks_shop_dbo.customers
ORDER BY id;

SELECT status, count(*) AS n, round(sum(amount), 2) AS total
FROM lakehouse.sql_server_to_databricks_shop_dbo.orders
GROUP BY status ORDER BY status;
Enter fullscreen mode Exit fullscreen mode

OLake Go adds _olake_id, _op_type, _olake_timestamp and _cdc_timestamp to each table, plus _cdc_start_lsn and _cdc_seqval on SQL Server tables. DESCRIBE EXTENDED shows the Iceberg provider and the deletion vectors in the table properties.

Step 7: Change rows in SQL Server and sync again

This is the step that separates CDC from a nightly export. Run these 12 changes, 7 inserts and 5 updates:

INSERT INTO dbo.customers (name, email, city, tier) VALUES
  (N'Maya Patel', 'maya@example.com', N'Pune', 'silver'),
  (N'Lucas Silva', 'lucas@example.com', N'São Paulo', 'bronze');
INSERT INTO dbo.orders (customer_id, product, amount, status) VALUES
  (9, 'Laptop', 1299.00, 'placed'), (9, 'Mouse', 25.50, 'placed'),
  (10, 'Monitor', 349.99, 'placed'), (3, 'Keyboard', 89.00, 'placed'), (7, 'Webcam', 79.90, 'placed');
UPDATE dbo.customers SET tier = 'gold',       updated_at = SYSUTCDATETIME() WHERE name = N'Liam Carter';
UPDATE dbo.customers SET city = N'Abu Dhabi', updated_at = SYSUTCDATETIME() WHERE name = N'Zara Ali';
UPDATE dbo.orders    SET status = 'delivered', updated_at = SYSUTCDATETIME() WHERE id IN (1, 4, 7);
Enter fullscreen mode Exit fullscreen mode

Give the capture job a few seconds, then click Sync Now again. The second sync read 12 records (855 bytes) from the change tables and finished in 20 seconds.

OLake UI job history for sql_server_to_databricks with two completed syncs, the first in 27 seconds and the second in 20 seconds

For customers, one new data file holds 4 rows (the 2 inserts and the new versions of the 2 updated rows), and one deletion vector retires the 2 old versions. orders has the same shape with 8 rows and 3 deleted positions.

OLake UI sync log with the Iceberg commit reports for orders and customers: addedDataFiles 1, addedDVs 1, addedRecords 8 and 4, addedPositionalDeletes 3 and 2

Re-run the customers query in Databricks. Liam Carter is now gold, Zara Ali lives in Abu Dhabi, and the two new customers, Maya Patel and Lucas Silva, are there.

Databricks SQL editor running SELECT on datazip.sql_server_to_databricks_shop_dbo.customers on a 2X-Small SQL warehouse, returning 10 rows with id, name, city and tier

_op_type tells you how each row arrived: r on the 6 rows untouched since the snapshot, c on the 2 inserts and u on the 2 updates. The orders roll-up matched SQL Server to the cent: 16 delivered for 8659.68, 18 placed for 10522.26 and 11 shipped for 6397.25.

Read the same tables from DuckDB and Spark

Nothing gets exported. Both engines attach Unity Catalog as an Iceberg REST catalog and ask Databricks for short-lived storage credentials, so no cloud keys are configured on their side.

INSTALL iceberg; LOAD iceberg;
INSTALL httpfs;  LOAD httpfs;
CREATE SECRET unity (TYPE iceberg, TOKEN '<personal access token>');
ATTACH 'lakehouse' AS uc (
  TYPE iceberg,
  ENDPOINT 'https://<workspace-url>/api/2.1/unity-catalog/iceberg-rest',
  SECRET unity,
  ACCESS_DELEGATION_MODE 'vended_credentials'
);
SELECT id, name, city, tier
FROM uc.sql_server_to_databricks_shop_dbo.customers
ORDER BY id;
Enter fullscreen mode Exit fullscreen mode
spark-sql \
  --packages org.apache.iceberg:iceberg-spark-runtime-4.0_2.13:1.10.0,org.apache.iceberg:iceberg-gcp-bundle:1.10.0 \
  --conf spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions \
  --conf spark.sql.catalog.uc=org.apache.iceberg.spark.SparkCatalog \
  --conf spark.sql.catalog.uc.type=rest \
  --conf spark.sql.catalog.uc.uri=https://<workspace-url>/api/2.1/unity-catalog/iceberg-rest \
  --conf spark.sql.catalog.uc.warehouse=lakehouse \
  --conf spark.sql.catalog.uc.token=<personal access token> \
  --conf spark.sql.catalog.uc.header.X-Iceberg-Access-Delegation=vended-credentials
Enter fullscreen mode Exit fullscreen mode

DuckDB 1.5.5 and Spark 4.0.1 with Iceberg 1.10.0 both returned the same 10 customers and the same orders roll-up as Databricks. On AWS or Azure, swap iceberg-gcp-bundle for iceberg-aws-bundle or iceberg-azure-bundle.

Tips from the run

  • Untick systranschemas. It has no capture instance, and selecting it fails the first sync with CDC is not enabled for stream dbo.systranschemas.
  • An empty change sync is usually timing. The capture job copies log records every few seconds, so a sync right after a write can find nothing; the next one picks the rows up.
  • Money becomes DOUBLE. decimal, numeric, money and float arrive as DOUBLE, so round at query time when you need exact decimal arithmetic. datetime2 has no zone and is read as UTC.
  • Schema changes need a capture instance. A new column is not in the existing capture instance. Create a new one, or turn on Manage Capture Instance, and OLake Go adds the column on the next sync.
  • Plan compaction. Each sync adds a small data file, and Spark's rewrite_data_files works through the same Unity Catalog endpoint.
  • Mind the token. An expired personal access token fails the next sync at the first catalog call; production jobs suit a service principal with OAuth machine-to-machine credentials.

How the SQL Server to Databricks options compare

Method Freshness Updates and deletes Where the data lands What you run
bcp export, then Auto Loader hours to daily full reloads or your own merge tables written by a Databricks pipeline an export script, a bucket and a Databricks job
Debezium, Kafka and Structured Streaming seconds yes, with your own merge logic Kafka topics, then tables from a streaming job Kafka, Kafka Connect, Debezium and a running Databricks job
Lakeflow Connect incremental, through change tracking or CDC yes tables managed by a Databricks ingestion pipeline a Lakeflow Connect pipeline on Databricks compute
OLake Go into Unity Catalog (this post) CDC on a schedule down to one minute yes, as deletion vectors Iceberg tables that Databricks, DuckDB, Spark and Trino read one Docker Compose stack, open source

If Databricks is the only reader and you want managed ingestion billed inside the workspace, Lakeflow Connect is the simpler path. This route earns its keep once a second engine needs the same rows, or when you want ingestion off Databricks compute.

It is also the wrong tool in two cases. SQL Server Express and Web editions cannot enable CDC, though Full Refresh + Incremental on an updated_at column still works there. Tables without a primary key replicate inserts only, because updates and deletes cannot be matched to a row.

FAQ

Can I do this without OLake UI?

Yes. The same Docker image runs from the command line: a source.json whose update_method is CDC, a destination.json with catalog_type set to unity, then discover and sync. Later runs add --state so only changes are replayed, and the container needs a persistent OLAKE_INDEX_DB_DIR for deletion vectors.

Does writing the tables use a Databricks warehouse?

No. OLake Go writes the Parquet files and deletion vectors from wherever Docker runs, without a Databricks warehouse or cluster. You spend Databricks compute only when you query.

How do I tell inserts from updates in Databricks?

Filter on _op_type: c for inserts, u for updates and d for deletes, with r for rows from the first snapshot. _cdc_timestamp and _cdc_start_lsn tell you when and where in the log each change came from.

Where to go from here

  • Add a table by running sys.sp_cdc_enable_table for it, then tick it on the job's Streams page.
  • Raise CDC retention with sys.sp_cdc_change_job before a planned pause, and shorten it once the job runs reliably every hour.
  • The guide with the data type table, the CLI tabs and the troubleshooting list is the SQL Server to Databricks page on olake.io.

If a step behaves differently on your server, leave a comment with what you saw and I will update the post.

Top comments (0)