如何为此运行查询

时间:2012-07-31 06:59:47

标签: tsql sql-server-2008-r2

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 谢谢, 史密斯

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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