Insert with select if the field is null

Asked

Viewed 134 times

-2

I have today this INSERT in JAVA running but I need to implement a new routine:

            public void gravarLogAbonoUnificado(TbLogAbonClickUnic entity,
            RetornoAuxDto auxDto) {


            STRING SQL = "INSERT INTO" +
            "TB_LOG_ABON_CLIK_UNIC" +
            "(NR_SEQU_LOG_LOG_CLICK_UNIC, NR_SEQU_TIPO_MOTI, CD_PODR) +
            "VALUES (?,?,?)";

            Query query = em.createNativeQuery(hql);

            Query.setParameter(1, entity.getTbLogEntrClickUnic().
            getNrSequeLogClikUnic()).

            Query.setParameter(2, (long) auxDto.getCodRetorno());

            //ESSE MEU CAMPO SE VIER NULL, PRECISA QUE SEJA INSERIDO //
              Query.setParameter(3, (long) auxDto.getCodRetorno());

            query.executeUpdate;

If my CD_PODR field is NULL it should insert with this select:

                  select p.nr_seque_item_podr from
            tb_tipo_grup_podr g,
            tb_tipo_item_podr p,
            where
            g.nr_seque_grup_podr = p.nr_seq_grup_podr and
            g.sg_grup_podr = '09'
            and
            p.sg_item_podr = '01'

How can I do that?

1 answer

1

Bruno, in this case you can make a check before the Insert, if the value that will pass in the values corresponding to column "CD_PODR" is NULL, you perform the following Insert:

STRING SQL = "INSERT INTO" +
        "TB_LOG_ABON_CLIK_UNIC" +
        "(NR_SEQU_LOG_LOG_CLICK_UNIC, NR_SEQU_TIPO_MOTI, CD_PODR)" +
        "(select CAMPO1, CAMPO2, CAMPO3, p.nr_seque_item_podr " +
        "  from tb_tipo_grup_podr g," +
        "       tb_tipo_item_podr p," +
        "  where" +
        "   g.nr_seque_grup_podr = p.nr_seq_grup_podr " +
        "   and g.sg_grup_podr = '09'" +
        "   and p.sg_item_podr = '01'" 

To perform an Insert through a select, in select itself you must return all fields that are expected to be inserted. I put the "FIELDS" representing that you have this information in your select, if you do not have and wanted to use what you are receiving in your method, you can do as follows this excerpt:

"(select" + VCAMPO1 + VCAMPO2 + VCAMPO3 + "p.nr_seque_item_podr " +

Here I put the "VCAMPS" as fields of your code and if your field CD_PODR is DIFFERENT FROM NULL, you perform the Insert that you do today.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.