Ответы пользователя по тегу SQL Server
  • Можно ли написать sql-запрос, который при выполнении разных условий будет записывать данные в разные поля?

    Сначала стоит сформировать запрос, который возвращает данные разного типа в разных столбцах, и уже его результаты инсертить.

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


    Вот пример более развёрнуто:
    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;
    Ответ написан
    Комментировать