开发者

SQL transform semi-colon list into relationship table

I currently have a code table containing a list of types (Type_ID, Description), but they are saved in another table as ID;;ID;;ID...etc

I am looking for a script that will take those ID's and place them in a relationship table c开发者_如何学Pythonorresponding to there Type ID

For example in table A the Type_ID entries could look like:

1;;2;;4

1

3;;4

1;;2;;3;;4

I am completely stumped on how to accomplish this and any help is appreciated.


First of all, I would probably recommend going the UDF route (so that you don't reinvent the wheel). However, given that this sounds like a one-off activity, you could just use the following:

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

The @output table variable now contains the mapping you're looking for. You can either copy from that to your destination at the end, or you can remove @output from the query and substitute equivalent inserts directly into your relationship table.


Probably the easiest way is to use a UDF (User Defined Function), such as the Split functions outlined here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜