現在のスキーマを正規化するのは良いことですが、テーブルを更新する 1 つの可能性を次に示します。
;with piv as (
-- Unpivot the data for ordering
select csCode, lane, [row], 1 as ordinal, stack1 as stack from MyTable
union all select csCode, lane, [row], 2 as ordinal, stack2 as stack from MyTable
union all select csCode, lane, [row], 3 as ordinal, stack3 as stack from MyTable
union all select csCode, lane, [row], 4 as ordinal, stack4 as stack from MyTable
union all select csCode, lane, [row], 5 as ordinal, stack5 as stack from MyTable
union all select csCode, lane, [row], 6 as ordinal, stack6 as stack from MyTable
)
, sort as (
-- Order the stacks
select *
, row_number() over (partition by csCode, lane, [row] order by case when stack = '' then 1 else 0 end, ordinal) as stackNumber
from piv
)
update a
set stack1 = (select stack from sort where csCode = a.csCode and lane = a.lane and [row] = a.[row] and stackNumber = 1)
, stack2 = (select stack from sort where csCode = a.csCode and lane = a.lane and [row] = a.[row] and stackNumber = 2)
, stack3 = (select stack from sort where csCode = a.csCode and lane = a.lane and [row] = a.[row] and stackNumber = 3)
, stack4 = (select stack from sort where csCode = a.csCode and lane = a.lane and [row] = a.[row] and stackNumber = 4)
, stack5 = (select stack from sort where csCode = a.csCode and lane = a.lane and [row] = a.[row] and stackNumber = 5)
, stack6 = (select stack from sort where csCode = a.csCode and lane = a.lane and [row] = a.[row] and stackNumber = 6)
from MyTable a
いくつかのCTEを使用して、スタックのピボットを解除して順序付けし、相関サブクエリで各スタックを更新しています。これをテーブル全体で実行するか、パフォーマンスを向上させるために必要に応じて where 句を指定できます。
ここにはいくつかの仮定があります。
- 「空白」データは空の文字列です。スペースとヌルがある可能性がある場合は、それをサニタイズするか、次のようなもので修飾します
ltrim(rtrim(coalesce(stack1, ''))) != ''
csCode, lane, row
候補キーを作成します (一意で、どれも null ではありません)。がそれ自体で主キーである場合、このクエリのいずれにもorcsCode
は必要ありません。lane
row