Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Insert Value That is In Table Being Inserted Into and Distinct Values from Joined Table

$
0
0

I'll try to show this through an example. I have 2 tables. tblMain is the main table that will be inserted into and tblValues contains the values that will be inserted. The 2 tables are joined on an ID field. tblValues has only one instance of an ID whereas tblMain can have multiple instances of the same ID. I need to insert only one instance of a record from tblValues into tblMain if there is a match. Also, there is a field called "AltValue" in tblMain, which I also need to be inserted into the new record in tblMain. AltValue will always have the same value for a given ID. Below is an example of the values the tables may have.

tblMain
ID	AltValue	City
1	A		Miami
1	A		Cleveland
2	B		Los Angeles

tblValues
ID	City
1	No City
2	No City

So with the above, I would need tblMain to look like below after the insert.

tblMain
ID	AltValue	City
1	A		Miami
1	A		Cleveland
2	B		Los Angeles
1	A		No City
2	B		No City

Below is the SQL that I have been trying but it ends up appending multiple instances.

Insert Into tblMain (ID, AltValue, City)
Select val.ID, tblMain.AltValue, val.City
From tblValues val Inner Join tblMain On
val.ID=tblMain.ID
WHERE
	EXISTS (
		SELECT *
		FROM tlMain Main
		WHERE Alt.ID = Main.ID)
If anyone can offer me some guidance, I'd appreciate it.


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>