I
I
Ilya2019-03-26 11:05:21
SQL
Ilya, 2019-03-26 11:05:21

Is it possible to write an sql query that, when different conditions are met, will write data to different fields?

Is it possible to write an sql query that, when different conditions are met, will write data to different fields?
For example:

case 
when t1.abc = 'A' then insert t1.abc into t1 (letter) -- если один результат - вставить в одно поле
when t1.abc = '1' then insert t1.abc into t1 (num) -- если другой результат - вставить в другое поле
end

Tell me, is it possible to implement this in sql?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin, 2019-03-26
@illaaa

First, you should form a query that returns data of different types in different columns, and insert its results.

insert into tb
select case when cond1 then 1 else null num,
       case when not cond1 then 'a' else null str
from ...

Here is a more detailed example:
create table test_a(num number, str varchar2(100));

insert into test_a
with
  generator as
   (select case
             when dbms_random.value() > 0.5 then dbms_random.string('p', 10)
             else to_char(trunc(dbms_random.value(0, 100)))
           end str
      from dual
      connect by level <= 50),
  classificator as
   (select str, case
                  when translate(str, chr(10)||'0123456789', chr(10)) is null then 'number'
                  else 'string'
                end type
      from generator)
select case
         when type = 'number' then to_number(str)
         else null
       end num,
       case
         when type = 'string' then str
         else null
       end str
  from classificator;
commit;

select * from test_a;

D
d-stream, 2019-03-26
@d-stream

Classic:

update table
set 
filed_n = case when условие1 then значение/выражение else field_n end
filed_m = case when условие2 then значение/выражение else field_m end
where ….

With insert - actually similar, only in case the negative branch will contain null

D
duhbox, 2019-03-26
@duhbox

True Oracle, but I think there should be a similar approach.
Here is a piece from my merge:
WHEN MATCHED THEN
UPDATE
SET DATE_E = CASE WHEN (DATE_B = MERGE_SUBQUERY.DATE_B$1)
THEN MERGE_SUBQUERY.DATE_E$1
ELSE DATE_E
END
You can update both fields according to different conditions for the desired value or for yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question