我有两张桌子:
表A:
ID Values
---------------
1 Q
2 B
3 TA
4 BS
TableB:
RawValue Value
------------------
[1][4] QBS
[2][1][3] BQTA
我需要使用给定的RawValues生成TableB值。 rawvalue中的每个[X]是TableA的ID coummn,并且应该替换为其值。
[1] [4]表示具有ID为1(Q)的TableA的值和具有ID(4)的TableA的值应该等于QBS。
任何人都可以建议一种方法吗?
这是我已经尝试过的:
update tableb set value=replace(rawvalue,'[' + (select id from tablea where id = cast(replace(replace(rawdata,'[',''),']','') as int)) + ']',
(select values from tablea where id = cast(replace(replace(rawdata,'[',''),']','') as int)))
顺便说一下:这仍然处于测试过程中,如果有人有更好的想法,我可以完全改变表格,行值格式和替换方法。
答案 0 :(得分:2)
declare @tableA table (id int, value varchar(50))
insert into @tableA (id, value)
select 1, 'Q' union all
select 2, 'B' union all
select 3, 'TA' union all
select 4, 'BS'
declare @tableB table (rawdata varchar(255), value varchar(255))
insert into @tableB (rawdata)
select '[1][4]' union all -- QBS
select '[2][1][3]' -- BQTA
update b
set value = (
select a.value + ''
from @tableA a
cross apply (select charindex ('[' + cast (a.id as varchar(50)) + ']', b.rawdata) as pos) p
where pos > 0
order by pos
for xml path('')
)
from @tableB b
select * from @tableB
P.S。我建议不要将字段命名为类似于保留关键字的字段(我的意思是值)。
答案 1 :(得分:0)
将RawValue
转换为XML,粉碎XML以在RawValue
中为每个值获取一行,并加入TableA
以获取值。
使用for xml path()
技巧连接TableA
。
update TableB
set Value = (
select T.Value as '*'
from (
select row_number() over(order by T2.X) as SortOrder,
TableA.Value
from (select cast(replace(replace(TableB.RawValue, '[', '<x>'), ']', '</x>') as xml)) as T1(X)
cross apply T1.X.nodes('x') as T2(X)
inner join TableA
on TableA.ID = T2.X.value('text()[1]', 'int')
) as T
order by T.SortOrder
for xml path('')
)