Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inserting to a join with merge

Status
Not open for further replies.

joeg99

Programmer
Mar 1, 2002
6
IE
Heya, just a curiosity question really, I've been playing with Merge and it rocks but I'm wondering if it can be used to solve a common problem. Often in a relational database you want to insert values into 2 tables at once, a simple example is:

DECLARE @Source TABLE(
Person VARCHAR(50),
Product VARCHAR(50)
)

INSERT INTO @Source (Person, Product) VALUES
( 'John Smith', 'Toaster'),
( 'John Smith', 'Hoover'),
( 'Jane Doe', 'Kettle'),
( 'Jane Doe', 'Blender')

DECLARE @Customers TABLE(
ID INT IDENTITY(1,1) NOT NULL,
Person VARCHAR(50)
)

DECLARE @Orders TABLE(
ID INT IDENTITY(1,1) NOT NULL,
CustomerID INT,
Product VARCHAR(50)
)

INSERT INTO @Customers
SELECT DISTINCT Person FROM @Source AS s
WHERE NOT EXISTS (SELECT * FROM @Customers AS cc WHERE cc.Person = s.Person)

INSERT INTO @Orders
SELECT c.ID, s.Product FROM @Customers AS c JOIN @Source AS s ON c.Person = s.Person
WHERE NOT EXISTS (SELECT * FROM @Orders o WHERE o.CustomerID = c.ID AND o.Product = s.Product)

SELECT * FROM @Customers
SELECT * FROM @Orders

I know I can tidy this up a fair bit just using MERGE but is there anyway I can use MERGE (or any other new stuff) to insert to both tables in 1 insert?

This really isnt important, I'm just checking out of curiosity, if anyone does know a way it would be cool though :p
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top