Sunday, March 4, 2007

Reorder data in a SQL table

Recently a friend asked whether I had any T-SQL code that would reorder data in a given table, such as the table in Listing 1 below. The table controls the order that certain reports are printed.

PK ID REPORT
100 1 Balance Sheet
101 2 Cash-Flow Statement
102 3 Expense Report
103 4 Income Statement
104 5 Profit and Loss Statement
105 6 Quarterly Financial Report
106 7 Securities and Exchange Commission
107 8 Statement of Capital
108 9 Statement of Earnings
109 10 Statement of Retained Earnings
Listing 1: Reports Table

The user would specify the id to change (oldid) and value to change it to (newid). However, it's not just updating the oldid to the new one, but also changing any impacted ids. For example, changing id 6 to 3 would result in 3 changing to 4, 4 changing to 5 and 5 changing to 6. The process would be reverse if changing id 3 to 6.

The following is one approach that works.

-- Add additional checks
IF( @oldid = @newid ) RETURN

IF( @oldid < @newid ) BEGIN
-- Decrement the ids
UPDATE Reports SET id = id - 1 WHERE id > @oldid AND id <= @newid
END ELSE BEGIN

-- Increment the ids
UPDATE Reports SET id = id + 1 WHERE id >= @newid AND id < @oldid
END


-- Change the specified id to the new value
UPDATE Reports SET id = @newid WHERE
pk = @pk

If the table doesn't have a primary key the following approach can be used:

-- Add additional checks
IF( @oldid = @newid ) RETURN

-- Change the oldid to an arbitrary value
UPDATE Reports SET id = -1 WHERE
id = @oldid

IF( @oldid < @newid ) BEGIN
-- Decrement the ids
UPDATE Reports SET id = id - 1 WHERE id > @oldid AND id <= @newid
END ELSE BEGIN

-- Increment the ids
UPDATE Reports SET id = id + 1 WHERE id >= @newid AND id < @oldid
END

-- Change the specified id to the new value
UPDATE Reports SET id = @newid WHERE
id = -1

No comments: