日期:2014-05-18  浏览次数:20485 次

急用,求各位大侠帮助!!!
数据库有两个字段 A B ,分别代表两种状态;  

现在要根实际情况,可以灵活的修改两个状态、、

假如A 有值,我把值赋给B ,假如B有值,我把值赋给A, 两个都没值,我就默认赋给A


怎样写存储过程呢??



------解决方案--------------------
case when .. else .. end
------解决方案--------------------
if ... else ....
------解决方案--------------------
SQL code

go
if OBJECT_ID('tbl')is not null
drop table tbl
go
create table tbl(
A varchar(3),
B varchar(3)
)
go
insert tbl
select 'aaa',null union all
select null,'bbb' union all
select null,null 
--
declare @str varchar(3)
set @str='bbb'
update tbl
set A=case when A is null then @str
      when A is not null and B is null then A else A end,
    B=case when A is null then B
      when A is not null and B is null then @STR else B end
select * from tbl
/*
A    B
aaa    bbb
bbb    bbb
bbb    NULL
*/

------解决方案--------------------
SQL code

go
if OBJECT_ID('tbl')is not null
drop table tbl
go
create table tbl(
A varchar(3),
B varchar(3)
)
go
insert tbl
select 'aaa',null union all
select null,'bbb' union all
select null,null 
--测试
declare @str varchar(3)
set @str='new'
update tbl
set A=case when A is null then @str
      when A is not null and B is null then A else A end,
    B=case when A is null then B
      when A is not null and B is null then @STR else B end
select * from tbl
/*
A    B
-------------
aaa    new
new    bbb
new    NULL
*/
    

这样看得明显点,注意对比两个字段的值