我目前有一个包含类型列表(Type_ID、描述)的代码表,但它们以 ID;;ID;;ID...等形式保存在另一个表中
我正在寻找一个脚本,它将获取这些 ID 并将它们放置在与类型 ID 对应的关系表中
例如,在表 A 中,Type_ID 条目可能如下所示:
1;;2;;4
1
3;;4
1;;2;;3;;4
我完全不知道如何做到这一点,任何帮助表示赞赏。
我目前有一个包含类型列表(Type_ID、描述)的代码表,但它们以 ID;;ID;;ID...等形式保存在另一个表中
我正在寻找一个脚本,它将获取这些 ID 并将它们放置在与类型 ID 对应的关系表中
例如,在表 A 中,Type_ID 条目可能如下所示:
1;;2;;4
1
3;;4
1;;2;;3;;4
我完全不知道如何做到这一点,任何帮助表示赞赏。
首先,我可能会建议走 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
table 变量现在包含您要查找的映射。您可以在最后从那里复制到您的目的地,或者您可以@output
从查询中删除并将等效插入直接替换到您的关系表中。