0

I need to make an insert, but before I need to compare the values ​​of the insert with other tables, so that I can also insert the values ​​of other tables, in the current table that I want to insert:

enter image description here

I don't know how to write the insert syntax

Insert into TABLE_3 (code, value, description)
values 123, 20000, teste

1 Answer 1

2

Consider the insert ... select ... syntax. The values() list comes handy for this.

insert into table_3(code, value, desription, subscription, value_percent, total_value)
select
    v.code,
    v.value,
    v.description,
    t1.subscription,
    t2.value_percent,
    v.value * t2.value_percent / 100.0 total_value
from (values (123, 20000, 'teste')) v(code, value, description)
inner join table_1 t1 on t1.code = v.code
inner join table_2 t2 on t2.subscription = t1.subscription
Sign up to request clarification or add additional context in comments.

5 Comments

I still need to do one last test to run the last inner join only if there is t1.code, if there is not, then you don't need to run it. t1.code IS NOT NULL
can help me please?
@rbrt: that's what the query does. If there is no match on t1.code, the row is not inserted.
I needed to return null on the missing columns. The columns that can be null are t1.subscription. This is posible?
@rbrt: ok, then you want left joins instead of inner joins. First change the last inner join to a left join, see if it does what you want. If that's not enough then change both.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.