简体   繁体   中英

Insert into Table A if key exists in Table B

Using BBj DBMS (it's weird). I have two tables TableA and TableB . TableA has columns Name and TableBId . I want to make certain that TableBId exists in TableB prior to inserting this new record into my table. I'm taking a blind insert (VIA a REST call) and am looking into making as few calls to the DB as possible.

Currently I have something along this lines of

INSERT INTO tablea (name, tablebid)
VALUES('Steven', '100')

I've tried appending

SELECT tablea.tablebid
FROM tablea join tableb

Without any luck

Edit : After suggestions, I'm trying.

INSERT INTO tableA (field1, field2, field3, tableBId, field5)
SELECT 'info', 'info2', 'info3', tableBId, 'info5'
FROM tableB WHERE tableBId = '01'  

However, I'm getting a duplicate key in write. To reiterate, I'm trying to make sure that tableBId exists in TableB, and if it doesn't I want the insert function to fail.

INSERT INTO tablea (name, tablebid)
SELECT 'Steven',tableid
FROM tableB
Where tableId=100

..

INSERT INTO trafficdetail (companycode, developmentcode, casenumber, questionnumber, answercode) 
SELECT '100', '1A', '000001300', questionnumber, '20' 
from trafficquesmast where questionnumber = '01'
INSERT INTO tablea (name, tablebid)
SELECT 'Steven', id
FROM tableb
where id = @id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM