2012-07-31 87 views
1

MyTable具有四列。如何为此运行查询

Condition1 | Condition2 | CondEquation | EquationResult 
---------------------------------------------------------  
    1  |  0  | C1 & C2 |  0 
    1  |  1  | C1 & C2 |  1 

EquationResult数据是选择C1 & C2。它是CondEquation的评估表达式。

如何使用SQL语句更新第4列。 有没有反正我可以写这个功能? SQL Server 2008 R2 谢谢, Smith

回答

0

当然。但我只能为您提供基于游标的解决方案,我希望这不是问题。

use testing 
-- create table test_01 (c1 int, c2 int, ce nvarchar(100), result int) 

insert into test_01 (c1, c2, ce) values (1, 0, 'c1 & c2') 
insert into test_01 (c1, c2, ce) values (1, 1, 'c1 & c2') 
insert into test_01 (c1, c2, ce) values (7, 3, 'c1 & c2') 
insert into test_01 (c1, c2, ce) values (2, 4, 'c1 | c2') 

declare @eq nvarchar(100) 
declare @sql_statement nvarchar(500) 

declare c cursor for select ce from test_01 
open c 
fetch next from c into @eq 

while @@fetch_status = 0 
    begin 
    -- update test_01 set result = (c1 & c2) where current of c 
    set @sql_statement = 'update test_01 set result = (' + @eq + ') where current of c' 
    exec sp_executesql @sql_statement 

    fetch next from c into @eq 
    end 

close c 
deallocate c 

select * from test_01 

这得出以下结果:

c1 c2 ce result 
1 0 c1 & c2 0 
1 1 c1 & c2 1 
7 3 c1 & c2 3 
2 4 c1 | c2 6 
+0

非常感谢你 – user1492518 2012-07-31 13:09:51

0

这里是一个脚本,将显示cEquationResult甚至当表中的数据变化,它只能处理比特运营商&和|

表来表示你的表:

create table t_test(condition1 bit, condition2 bit, condition3 bit, CondEquation varchar(20)) 
insert t_test values(1,0, 0, 'c1&c2|c3') 
insert t_test values(1,1, 1, 'c1&c2 | c3') 

go 

函数来计算所算出的比特。是的,它是一个平均值一个:

create function f_t(@condition1 bit, @condition2 bit, @condition3 bit, @CondEquation varchar(10)) 
returns bit 
as 
begin 
declare @result bit 
;with a as 
(
select replace(replace(replace(replace(@CondEquation, 'c1',@condition1), 'c2',@condition2), 'c3',@condition3), ' ','') n 
), 
b as 
(
select n, 1 rn from a 
union all 
select stuff(n, patindex('%&%', n) - 1, 3 , case when substring(n, patindex('%&%', n) - 1, 3) like '%0%' then 0 else 1 end), rn+1 
from b 
where patindex('%&%', n)> 0 
), c as 
(
select n from (
select n, row_number() over (order by rn desc) rn2 from b 
) a where rn2 = 1 
), d as 
(
select n, 1 rn from c 
union all 
select stuff(n, patindex('%|%', n) - 1, 3 , case when substring(n, patindex('%|%', n) - 1, 3) like '%1%' then 1 else 0 end), rn+1 
from d 
where patindex('%|%', n)> 0 
), e as 
(
select n from (
select n, row_number() over (order by rn desc) rn2 from d 
) a where rn2 = 1 
) 
select @result=n from e 
return @result 
end 
go 

增加额外的字段,以显示所算出的比特

ALTER TABLE t_test ADD cEquationResult AS 
dbo.f_t(condition1, condition2, condition3, CondEquation) 

测试脚本:

select * from t_test 
+0

谢谢你的答案。实际上,我在视图中具有上述数据,条件1,条件2等可以是任意数量的列,因为这变得更加复杂。 – user1492518 2012-07-31 13:04:20

+0

@ user1492518我怀疑它比描述更复杂,这就是为什么我添加额外的列,对于每个条件,您需要将其添加到函数的参数,并相应地更改替换语句。该功能可以轻松添加到视图中。只需改变视图并将其添加为列:dbo.f_t(condition1,condition2,condition3,CondEquation)cEquationResult – 2012-07-31 13:47:40