如何根据第二列值插入第三列值

时间:2016-08-15 13:17:14

标签: sql sql-server

如何将值插入具有第二列值输出的表

我想根据2列值输出

插入3列值

查询

insert into table1 (id, type, desc)
values
select id#,
case 
when CUSTOMER_CODE = 'I' then (select type# from customertype where typecode = 'abc')
when CUSTOMER_CODE = 'L' and LEN(NUMBER) > 0 then (select type# from customertype where typecode = 'def')   
end,
case
when CUSTOMER_TYPE = 'M' and type  = 1 then 'dwcerf'
when CUSTOMER_TYPE = 'O' and type = 2 then 'scef'
End
from table2

type = 1,type = 2是第二列的输出

如何做到这一点,请建议

2 个答案:

答案 0 :(得分:0)

您可以使用子查询:

insert into table1 (id, type, desc)
SELECT  *,
        case
            when CUSTOMER_TYPE = 'M' and type  = 1 then 'dwcerf'
            when CUSTOMER_TYPE = 'O' and type = 2 then 'scef'
            End
FROM (
    select id#,
    case 
    when CUSTOMER_CODE = 'I' then (select type# from customertype where typecode = 'abc')
    when CUSTOMER_CODE = 'L' and LEN(NUMBER) > 0 then (select type# from customertype where typecode = 'def')   
    end as [type]
    from table2
    ) as p

答案 1 :(得分:0)

如果您需要中间变量参与进一步的计算,请使用APPLY。

writer.putContent(new ByteArrayInputStream(mergedDocument));

希望insert into table1 (id, type, desc) select id#, ca.var, case when CUSTOMER_TYPE = 'M' and ca.var = 1 then 'dwcerf' when CUSTOMER_TYPE = 'O' and ca.var = 2 then 'scef' End from table2 cross apply ( select var = case when CUSTOMER_CODE = 'I' then (select type# from customertype where typecode = 'abc') when CUSTOMER_CODE = 'L' and LEN(NUMBER) > 0 then (select type# from customertype where typecode = 'def') end) ca typecode中是唯一的,否则您将收到错误。