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

4

2 回答 2

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
于 2012-07-31T11:40:59.767 回答
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
于 2012-07-31T12:34:52.990 回答