2

現在、タイプ (Type_ID、Description) のリストを含むコード テーブルがありますが、それらは ID;;ID;;ID... として別のテーブルに保存されています。

これらの ID を受け取り、タイプ ID に対応する関係テーブルに配置するスクリプトを探しています。

たとえば、テーブル A の Type_ID エントリは次のようになります。

1;;2;;4
1
3;;4
1;;2;;3;;4

これを達成する方法に完全に困惑しており、どんな助けも大歓迎です。

4

2 に答える 2

3

まず第一に、UDF ルートを使用することをお勧めします (車輪の再発明を避けるため)。ただし、これは 1 回限りのアクティビティのように聞こえるため、次のように使用できます。

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、クエリから削除して、同等の挿入を関係テーブルに直接置き換えることができます。

于 2010-08-11T16:02:03.837 に答える
2

おそらく最も簡単な方法は、こちらで概説されている Split 関数UDFなどの (ユーザー定義関数)を使用することです。

于 2010-08-11T15:46:24.607 に答える