0

I would like to insert data into an Oracle database, but the column name where I want to insert isn't known in the first step, it depends on the user's choice.

For example:

colonne varchar(12) :=null;
...
case
  WHEN MOIS1 = 1 THEN 
    colonne :='col1';    
  WHEN MOIS1 = 2 THEN
    colonne :='col2';
  WHEN MOIS1 = 3 THEN
    colonne :='col3';
...    
insert into Mytable ( user_id, name, colonne, ...)

and it depend to the user colonne can be col1, col2 or col3, is it possible to do that?

1 Answer 1

1

You can't use a variable as a column name like that, no. You could use dynamic SQL to build the insert statement and then bind the value, but since you have a limited choice you could also do this:

insert into mytable(user_id, name, col1, col2, col3)
values (v_user_id, v_name,
    case when mois1 = 1 then v_value else null end,
    case when mois1 = 2 then v_value else null end,
    case when mois1 = 3 then v_value else null end
);

You insert something into all three columns, but the case statements within the values clause determine whether you insert null or your actual value - you'll only put the real value into one of the three columns.

SQL Fiddle.

Sign up to request clarification or add additional context in comments.

4 Comments

I will try it right now, but is it possible to use case inside the sql statement ?
@devosJava - yes; I've added an SQL Fiddle to demonstrate.
Sorry, but i have another constraint,its about insert .... select (...) the logic still the same ?
@devosJava - yes it is; another SQL Fiddle to demonstrate. Not sure why you didn't just try it though...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.