这是我的问题:如何将{1}}列从1级更新为6?
id Code amount formula level
-----------------------------------------------
1 A10 0.00 A07 5
2 A02 0.00 (A01+A04)*A05 2
3 A03 0.00 A02+A04 3
4 A04 40.00 1
5 A05 50.00 1
6 A06 0.00 A03+A01 4
7 A0 0.00 A04+A07+A10+A01+A02+A03 6
8 A01 20.00 1
9 A07 0.00 (A03) 4
10 A08 0.00 (A01) 2
答案 0 :(得分:2)
我可能会做出许多非常通用的假设,以便您的目的更不用说这是完全未经测试的。但也许这是你尝试的起点。
declare @id int;
declare @level int = 2;
declare @code varchar(8);
declare @amt decimal(10, 2)
while @level <= (select max(id) from T)
begin
set @id = 1;
while @id <= (select max(id) from T)
begin
set @code = null; set @amount = null;
select @code = Code, @amount = amount from T where id = @id and level = @level - 1;
if @code is not null update T set formula = replace(formula, @code, '(' + cast(amount as varchar(16)) + ')'
set @id = @id + 1;
end
set @level = @level + 1;
end
set @id = 1;
while @d <= (select max(id) from T)
begin
-- use dynamic sql to evaluate each of the expression (assuming they're valid)
declare @sql nvarchar(max) = N'declare @f decimal(10, 2); select @f = ' +
(select formula from T where id = @id);
sp_executesql @sql, 'decimal(10, 2)', @amt output;
update T set amount = @amt where id = @id;
set @id = @id + 1;
end