2012-07-31 43 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