Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I lookup a value in a table and insert it into another table?

Tags:

sql

sql-server

The SQL below selects distinct rows from a table and inserts them into a third table. It works fine.

There is a third column (STID) that I want to insert into the destination table. In the SourceData table, there is a column name STFP. I need to lookup the value of STFP in a third table, STS table, and get the value of STID. How do I get the value of STID?

INSERT INTO DestinationTable(CTYFP, CTYNAME)
SELECT DISTINCT CTYFP , CTYNAME
FROM SourceData
like image 830
DenaliHardtail Avatar asked Dec 31 '25 18:12

DenaliHardtail


1 Answers

Just join to the other table:

INSERT INTO DestinationTable (CTYFP, CTYNAME, STFP)
SELECT DISTINCT sd.CTYFP, sd.CTYNAME, STS.STFP
FROM SourceData sd
JOIN STS on SIS.STID = sd.STID;

Note: Your question did not post table column names, so I have guessed. You may have to adjust to suit your actual column names.

like image 179
Bohemian Avatar answered Jan 02 '26 10:01

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!