SQL Server Table Reconciliation

SQL Server Table Reconciliation

Guides an agent to compare identical tables across two SQL Server instances with Python and Arrow, detecting missing rows, mismatches and schema drift, then writing a reconciliation report.

Skill files2 files

scripts/

SKILL.md159 lines
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

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 13,689 prompts

More by @OpenSourceBuffGuy

See all
Quiet Kyoto autumn travel vlog, 30 seconds prompt image

Quiet Kyoto autumn travel vlog, 30 seconds

Generates a slow, natural 30-second autumn travel vlog in Kyoto of the woman from a reference image, with short casual dialogue, handheld camera and film grain, avoiding an ad look.

video-prompt, vlog, reference-image, character-consistency, handheld, film-grain, home-video, travel, japan, multi-shot, lip-sync, natural-light, guardrails, seedance, for-content-creators, timed-beats, long-form, casual, candid, autumn

Ice heroine fights hunters in Seoul parking garage prompt image

Ice heroine fights hunters in Seoul parking garage

Plans a 30-second supernatural action film where an ice-powered heroine defends a puppy from hunters in a Seoul parking garage, with identity locked to two reference images.

video-prompt, kling, timed-beats, multi-shot, action, martial-arts, visual-effects, character-consistency, reference-image, korea, cityscape, night-scene, slow-motion, tracking-shot, cinematic, creatures, film-score, negative-prompt, dramatic-lighting, neon, advanced, lip-sync, woman

Floating pan-fried gyoza with ponzu splash prompt image

Floating pan-fried gyoza with ponzu splash

Generates a macro food photograph of pan-fried gyoza floating in zero gravity with a ponzu splash, sesame droplets and green onion confetti under warm side light.

image-prompt, food-photography, photorealistic, cinematic, macro, nano-banana, dramatic-lighting, vertical-format, still-life, cooking, japan, golden-hour, for-photographers, restaurants, bokeh, advanced

Reviews

Loading reviews…

Discussion

Loading comments…