0

My query.

INSERT INTO TARGET_TABLE (SELECT DATA FROM TABLE_DATA WHERE TYPE = 'HEADER') VALUES
(SELECT DATA FROM TABLE_DATA WHERE TYPE = 'ITEMS')

In this query I am trying to insert data into TARGET_TABLE. TABLE_DATA will have data in the below format

SELECT DATA FROM TABLE_DATA WHERE TYPE = 'HEADER'
Result COUNTRY,ID,NAME

SELECT DATA FROM TABLE_DATA WHERE TYPE = 'ITEMS'
Result 'IN','123','xyz' 

So I am expecting the below

INSERT INTO TARGET_TABLE (COUNTRY,ID,NAME) VALUES ('IN','123','xyz')

Any thoughts on this?

1
  • Any Inputs / Suggestions on this topic? Commented Oct 4, 2019 at 11:46

2 Answers 2

1

select case is what you need

INSERT INTO TARGET_TABLE 
(SELECT case when type='HEADER' then COL1 else 'aa' END
     ,case when type='HEADER' then COL2 else 'bb' END
     ,case when type='HEADER' then COL3 else 'cc' END
     ,case when type='HEADER' then COL4 else 'dd' END
FROM TABLE_DATA )
Sign up to request clarification or add additional context in comments.

1 Comment

Nope, I am trying to achieve dynamic data, but in your case you are hard coding the columns
1

You need to use a dynamic query like the following:

BEGIN
EXECUTE IMMEDIATE 
  'INSERT INTO TARGET_TABLE ( ' 
  || SELECT DATA FROM TABLE_DATA WHERE TYPE = 'HEADER' 
  || ') VALUES ('
  || SELECT DATA FROM TABLE_DATA WHERE TYPE = 'ITEMS' 
  || ')';
END;
/

Cheers!!

7 Comments

Thanks for your response, However when I use the below <pre><code> INSERT INTO TARGET (SELECT REPLACE( RAW_DATA,' ',',') FROM TABLE_DATA WHERE ROW_NO = 1) VALUES (SELECT ''''|| REPLACE( RAW_DATA,' ',''',''') ||'''' FROM TABLE_DATA WHERE ROW_NO <> 1) </code></pre> Its giving error missing SELECT keyword.
I am not sure which platform you are executing the query. If you execute the code from my answer on SQL*Plus or SQL Developer then you will be able to achieve the desired result and then you need to convert the code to what is supported in your platform.
I am executing in SQL Developer
What is the result of the DBMS_OUTPUT.PUT_LINE('INSERT INTO TARGET_TABLE ( ' || SELECT DATA FROM TABLE_DATA WHERE TYPE = 'HEADER' || ') VALUES (' || SELECT DATA FROM TABLE_DATA WHERE TYPE = 'ITEMS' || ')');
Its just as the below 'INSERT INTO TARGET_TABLE ( ' || SELECT DATA FROM TABLE_DATA WHERE TYPE = 'HEADER' || ') VALUES (' || SELECT DATA FROM TABLE_DATA WHERE TYPE = 'ITEMS' || ')'
|

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.