-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGeneratePaddedSequentialNumbers.sql
More file actions
42 lines (34 loc) · 1.01 KB
/
Copy pathGeneratePaddedSequentialNumbers.sql
File metadata and controls
42 lines (34 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
Purpose:
- Preview or assign deterministic, zero-padded sequence values to existing rows.
Safety:
- Changes data only when @ApplyChanges = 1. The default execution rolls back.
Requirements:
- SQL Server 2012 or later.
Customization:
- Replace dbo.SampleEntity, entity_id, and display_sequence.
- Choose a stable ORDER BY column; never use ORDER BY (SELECT NULL) for persisted numbering.
*/
SET XACT_ABORT ON;
DECLARE @ApplyChanges BIT = 0;
BEGIN TRANSACTION;
;WITH NumberedRows AS
(
SELECT
entity_id,
RIGHT(REPLICATE('0', 6) + CONVERT(VARCHAR(20), ROW_NUMBER() OVER (ORDER BY entity_id)), 6) AS padded_number
FROM dbo.SampleEntity
)
UPDATE target
SET display_sequence = numbered.padded_number
OUTPUT
inserted.entity_id,
deleted.display_sequence AS previous_value,
inserted.display_sequence AS proposed_value
FROM dbo.SampleEntity AS target
JOIN NumberedRows AS numbered
ON numbered.entity_id = target.entity_id;
IF @ApplyChanges = 1
COMMIT TRANSACTION;
ELSE
ROLLBACK TRANSACTION;