简体   繁体   中英

SQL INSERT SELECT from Table2 to Table3

I'm trying to insert ID from Table1 and Table2 into Table3.My table design is:

Table1:
Id_Table1
field1 etc.

Table2:
Id_Table2
field1 etc.

Table3:
Id_Table3
Id_Table1_FK
Id_Table2_FK

I do this when I save records for Table1. Meanwhile I have Datagridview in my form, which uses comboboxcell to view records from Table2. When I select some record from Table2, both ID's (Table1 & Table2) needs to be inserted into Table3.

Here is my code so far (obviously wrong):

INSERT INTO Table3 (Id_Table3, Id_Table1, Id_Table2) 

SELECT Id_Table2 FROM Table2 WHERE serial_no=" & MyDGV.CurrentRow.Cells(0).Value.ToString

VALUES (Id_Table3_seq.nextval, Id_Table1_seq.currval,????)

So, my problem stucks with Id_Table2 which needs to be selected first by Datagridview.Row cell value, and then result passed like a parameter to Table3. Any suggestions ? Probably an easy one, I just don't know how to start...

If I got your point right, this is what you need maybe?

INSERT INTO Table3 (Id_Table3, Id_Table1, Id_Table2) 
VALUES (Id_Table3_seq.nextval, Id_Table1_seq.currval,(
SELECT Top 1 Id_Table2 FROM Table2 WHERE serial_no='" & MyDGV.CurrentRow.Cells(0).Value.ToString & "'
))

Edited: Added Top 1 to make sure the subquery will only return 1 recordset. It's optional if the field you are selecting is unique.

Use a SELECT that returns constant valus:

INSERT INTO Table3 (Id_Table3, Id_Table1, Id_Table2) 
select Id_Table3_seq.nextval, 
       Id_Table1_seq.currval,
       Id_Table2
FROM Table2 
WHERE serial_no='" & MyDGV.CurrentRow.Cells(0).Value.ToString & "';

In general you should not concatenate values into a SQL string. Use a prepared statement with parameters (placeholders) instead (don't know how that is done in VB.net)

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