我从b表select出来一些字段数据,要插入到a表中。
插入前要判断b表其中一个字段,完后决定往a表插正值还是负值比如b表为
order  num  status_flag
r001    5         1
r002    6         0
r003    7         0
r004    8         1
如果status_flag为1就往a表里插正的num,如果为0就往a表里插负的num
a表就应该为
order  num  status_flag
r001    5         1
r002    -6         0
r003    -7         0
r004    8         1

这个语句怎么写?
inert into a(order,num,status_flag)
select order,num,status_flag from b
if b.status_flag =1
then
    num=num
else
 if
  b.status_flag =0
then
   num=-num
 endif
endif
是这样写吗?

解决方案 »

  1.   

    inert into a(order,num,status_flag)
    select order,
           -num* (status_flag*2-1)
           status_flag 
    from b
      

  2.   


    --1
    inert into a(order,num,status_flag)
    select order,num=case when status_flag =1 then num
    else -num end,
    status_flag from b--2
    inert into a(order,num,status_flag)
    select order,
      num* (status_flag*2-1)
      status_flag  
    from b
      

  3.   

    inert into a(order,num,status_flag)
    select order,
    num=
    case  
    when status_flag='1' then num else -1*num 
    end
    status_flag from b
      

  4.   


    --> 测试数据:[test]
    if object_id('[test]') is not null 
    drop table [test]
    create table [test](
    [order] varchar(4),
    [num] int,
    [status_flag] int
    )
    insert [test]
    select 'r001',5,1 union all
    select 'r002',6,0 union all
    select 'r003',7,0 union all
    select 'r004',8,1if object_id('[a]') is not null 
    drop table a
    create table a(
    [order] varchar(4),
    [num] int,
    [status_flag] int
    )
    goinsert a 
    select [order],
    case when [status_flag]=0 then -[num] else [num] end,[status_flag]
    from test
    go
    select * from a
    /*
    order num status_flag
    -----------------------------------
    r001 5 1
    r002 -6 0
    r003 -7 0
    r004 8 1
    */
      

  5.   

    步高点读机,哪里不会点哪里,学习英语So Easy 
      

  6.   

    插入的时候用case判断一下就行了
      

  7.   

    INSERT INTO A(Order,Num,Status_Flag)
    SELECT Order
    , CASE Status_Flag = 1 THEN -Num ELSE Num END
    , Status_Flag
    From B
      

  8.   

    我试了,
    insert into affairs_records(
    orno,item,cwar,qstk)
    select t.t$orno+'-'+t.t$pono,t.t$item,t.t$cwar,
    case 
    when
          t.t$koor='21' And t.t$kost='17'     
    then
    '-'+t.t$qstkwhen 
         t.t$kost='6' Or t.t$kost='4'
    then
           cast(t.t$qstk AS varchar(50))end as t$qstk
    from 
    openquery(erp,'Select t$cwar,t$item,t$koor,t$kost,t$orno,t$pono,t$qstk,t$trdt From affairs_1') t
    因为在oracle的affairs_1表里t$qstk全都是正数,我通过判断条件人为的加上负号。结果oracle里本来就是正数的数据取过来全都是null,这是什么原因?
    在oracle里,t$qstk是double类型,我的affairs_records表中qstk字段是varchar(50)类型。
    请指教,感谢!