Прежде всего, я бы порекомендовал пойти по маршруту UDF (чтобы не изобретать велосипед). Однако, учитывая, что это звучит как разовое занятие, вы можете просто использовать следующее:
declare @output table (parentKey int, value int)
declare @values table (idx int identity(1, 1), parentKey int, value varchar(255))
-- Modify the below query to capture the data from your table
insert into @values (parentKey, value) values(1, '1;;2;;4'),(2, '1'),(3, '3;;4'),(4, '1;;2;;3;;4')
declare @i int
declare @cnt int
select @i = MIN(idx) - 1, @cnt = MAX(idx) from @values
while(@i < @cnt)
begin
select @i = @i + 1
declare @value varchar(255)
declare @key int
select @value = value, @key = parentKey from @values where idx = @i
declare @idx int
declare @next int
select @idx = 1
while(@idx <= LEN(@value))
begin
select @next = CHARINDEX(';;', @value, @idx)
if(@next > @idx)
begin
insert into @output (parentKey, value) values(@key, SUBSTRING(@value, @idx, @next - @idx))
select @idx = @next + 2
end
else
begin
insert into @output (parentKey, value) values(@key, SUBSTRING(@value, @idx, LEN(@value) - @idx + 1))
select @idx = LEN(@value) + 1
end
end
end
select * from @output
Табличная переменная @output
теперь содержит искомое отображение. Вы можете либо скопировать из этого в конечный пункт назначения в конце, либо удалить @output
из запроса и заменить эквивалентные вставки непосредственно в таблицу отношений.