1

I have been trying to solve my problem but could not find the answer. Oracle db.

I have table context with looks like:

| contextId | customer |
 ----------------------
|         1 | John     |
|         2 | David    |

I have another table setting:

| contextId | settingName | settingValue |
 ----------------------------------------
|         1 | Happiness   |            6 |
|         1 | Sadness     |            3 |

What I would like is to insert David in setting, while copying the settingName and settingValue of John (contextId = 1).

Result should look like:

| contextId | settingName | settingValue |
 ----------------------------------------
|         1 | Happiness   |            6 |
|         1 | Sadness     |            3 |
|         2 | Happiness   |            6 |
|         2 | Sadness     |            3 |

Thanks

3 Answers 3

4
INSERT INTO SETTING
  SELECT (SELECT CONTEXTID FROM CONTEXT WHERE CUSTOMER = 'DAVID'),
         SETTINGNAME,
         SETTINGVALUE
    FROM SETTING
   WHERE CONTEXTID = 1
Sign up to request clarification or add additional context in comments.

Comments

1

If your requirement is to use the customer names 'David' and 'John', then you need a join:

INSERT INTO SETTING (CONTEXTID, SETTINGNAME, SETTINGVALUE)
  SELECT 
    (SELECT CONTEXTID FROM CONTEXT WHERE CUSTOMER = 'David'),
    s.SETTINGNAME,
    s.SETTINGVALUE
  FROM CONTEXT AS c INNER JOIN SETTING AS s 
  ON s.CONTEXTID = c.CONTEXTID
  WHERE c.CUSTOMER = 'John'

2 Comments

This is actually what I needed because context id is different depending on the environments this query is run (but the values are the same). That's why I mark this answer as accepted. But the answer of Chaitanya Kotha is also good.
Note that I had to remove 'AS' from the query for it to work though.
0

Declared a separate variable to hold the contextId of customer - David. And inserting the multiple values available in setting table for customer - David.

DECLARE
  l_contextId context.contextId%TYPE;
BEGIN

  SELECT
    contextId
  INTO
    l_contextId
  FROM
    context
  WHERE
    customer = 'David';

END; 


INSERT INTO setting
(contextId, settingName, settingValue)
SELECT l_contextId, settingName, settingValue
FROM setting
WHERE contextId = 1

Comments

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.