1
---
2
name: sql-server-table-reconciliation
3
description: "Use when: comparing SQL Server tables across instances, data migration validation, ETL verification, row mismatch detection, schema drift, reconciliation report, production vs staging comparison. Uses mssql-python driver with Apache Arrow for fast columnar data transfer and comparison."
4
---
5
6
# SQL Server Table Reconciliation
7
8
Compare identical tables across two SQL Server instances using Python with `mssql-python` driver and Apache Arrow. Detect missing rows, column mismatches, schema drift, and produce a reconciliation report.
9
10
## Workflow
11
12
1. Collect connection details for source and target
13
2. Identify primary key / composite key
14
3. Detect schema differences
15
4. Extract data via Arrow for efficient columnar transfer
16
5. Compare rows and columns
17
6. Generate reconciliation report
18
19
## Collect Inputs
20
21
| Parameter | Required | Description |
22
|-----------|----------|-------------|
23
| Source server | Yes | Source SQL Server (e.g. `prod-server.database.windows.net`) |
24
| Source database | Yes | Source database name |
25
| Target server | Yes | Target SQL Server (e.g. `staging-server.database.windows.net`) |
26
| Target database | Yes | Target database name |
27
| Tables | Yes | Comma-separated `schema.table` names, or `schema.*` wildcard (e.g. `dbo.Orders,dbo.Items` or `dbo.*`) |
28
| Auth mode | Yes | `sql` (user/password) or `entra` (Azure AD/token) |
29
| Primary key | Auto-detect | Column(s) forming the row identity. Auto-detect from metadata if not provided. |
30
| Columns to compare | All | Subset of columns, or all non-PK columns |
31
| Chunk size | `100000` | Rows per batch for large tables |
32
| Output format | `console` | `console`, `csv`, `parquet`, or `json` |
33
34
## Bundled Script
35
36
The reconciliation logic is provided as a standalone script at `scripts/reconcile.py`. Invoke it with the appropriate arguments based on user inputs:
37
38
```bash
39
python scripts/reconcile.py \
40
--source-server <source_server> \
41
--source-database <source_database> \
42
--target-server <target_server> \
43
--target-database <target_database> \
44
--tables "<table_spec>" \
45
--auth <sql|entra> \
46
--chunk-size <chunk_size> \
47
--output <console|csv|json>
48
```
49
50
### Optional arguments
51
52
| Argument | Description |
53
|----------|-------------|
54
| `--primary-key` | Comma-separated PK column(s). Omit to auto-detect. |
55
| `--columns` | Comma-separated columns to compare. Omit to compare all non-PK columns. |
56
57
### Example invocations
58
59
Single table with SQL auth:
60
61
```bash
62
python scripts/reconcile.py \
63
--source-server prod-server.database.windows.net \
64
--source-database ProdDB \
65
--target-server staging-server.database.windows.net \
66
--target-database StagingDB \
67
--tables "dbo.Orders" \
68
--auth sql \
69
--output console
70
```
71
72
Wildcard with Entra auth and CSV output:
73
74
```bash
75
python scripts/reconcile.py \
76
--source-server prod-server.database.windows.net \
77
--source-database ProdDB \
78
--target-server staging-server.database.windows.net \
79
--target-database StagingDB \
80
--tables "dbo.*" \
81
--auth entra \
82
--output csv
83
```
84
85
### Prerequisites
86
87
Install required packages before running:
88
89
```bash
90
pip install mssql-python pyarrow pandas
91
```
92
93
## Comparison Rules
94
95
- **Normalize types before comparing**: cast decimals to same precision, trim strings, normalize datetime to UTC
96
- **NULL handling**: `NULL == NULL` is considered a match (both sides missing = no diff)
97
- **Ignore row order**: always compare by PK join, never positional
98
- **Large tables**: chunk extraction with `OFFSET/FETCH` or `ROW_NUMBER()` partitioning
99
100
## Hash-Based Optimization (for large tables)
101
102
When table has >1M rows, generate a hash pre-check:
103
104
```sql
105
SELECT {pk_cols},
106
HASHBYTES('SHA2_256', CONCAT_WS('|', col1, col2, ...)) AS row_hash
107
FROM {table}
108
```
109
110
Compare hashes first; only fetch full rows for mismatched hashes. This reduces data transfer significantly.
111
112
## Report Format
113
114
```
115
Reconciling dbo.EMPLOYEES...
116
Reconciling dbo.DEPARTMENTS...
117
Reconciling dbo.JOBS...
118
119
--- dbo.EMPLOYEES ---
120
Source: 107 Target: 107
121
Missing: 0 Extra: 0 Mismatches: 0
122
Result: ✓ IDENTICAL
123
124
--- dbo.DEPARTMENTS ---
125
Source: 27 Target: 27
126
Missing: 0 Extra: 0 Mismatches: 3
127
Result: ✗ DIFFERENCES FOUND
128
129
--- dbo.JOBS ---
130
Source: 19 Target: 19
131
Missing: 0 Extra: 0 Mismatches: 0
132
Result: ✓ IDENTICAL
133
134
=== Summary: 2 passed, 1 failed, 0 skipped / 3 tables ===
135
```
136
137
When a single table is provided, include full detail (schema drift, sample rows, mismatches). When multiple tables, use the compact per-table format above with full detail only for tables with `FAIL` status.
138
139
## Performance Considerations
140
141
| Scenario | Strategy |
142
|----------|----------|
143
| < 100K rows | Single Arrow fetch, in-memory pandas compare |
144
| 100K–1M rows | Chunked extraction (100K batches), streaming comparison |
145
| > 1M rows | Hash pre-check → only fetch mismatched rows |
146
| Wide tables (100+ cols) | Compare PK + hash first, drill into specific columns on mismatch |
147
| Network-constrained | Use Arrow columnar format (10-50x smaller than row-by-row) |
148
149
## Constraints
150
151
- Always use `mssql-python` driver (not pyodbc, pymssql)
152
- Always use Apache Arrow via cursor (`cursor.arrow()`) for data extraction
153
- Connection MUST use connection string format, not keyword arguments (kwargs like `encrypt=True` throw errors)
154
- Never compare without identifying PK first — ask user if auto-detect fails
155
- Handle connection failures gracefully with retry logic
156
- **Never hardcode credentials** in generated scripts — use `os.environ` / `getpass` (env vars: `MSSQL_USER`, `MSSQL_PASSWORD`)
157
- Do not print credentials in output or logs
158
- Use parameterized queries (`?` placeholders) for metadata lookups — never f-string interpolate user input into SQL
159