2 merge statements into 2 targets from 1 source

Sql server 2k8

I'm on my phone right now so I won't be posting code but can later if necessary
 
I have a source CTE (srccte) and a merge statement following it using a target (tgttbl) -
Works perfect !
I then wanted to add another target - a second table.  So I wrote another Merge statement after the first Merge statement and I get an error saying that SRCCTE is undefined.

Note that if I comment out either the first or the second MERGE statement the entire code works perfect - it's only when trying to use both that the error occurs.

How would one go about using a second target table? Would I use just one Merge statement and work the second table into the one statement?

Thanks
LVL 25
dgrafxAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Brian CroweDatabase AdministratorCommented:
Although you can reference a cte multiple times within a single query you can't across multiple queries.  You will either need to duplicate the cte logic for the second merge statement or dump the data into a temp table to be used by both merges.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dgrafxAuthor Commented:
Just read that - I was just going to modify the question but was messing with creating a temp table - do you have any code handy for creating a temp table?

thanks
Brian CroweDatabase AdministratorCommented:
Just use the same CREAT TABLE DDL that you would use for a permanent table:

CREATE TABLE #Table
(
	ID				INT,
	Profile_ID		INT
);

Open in new window

dgrafxAuthor Commented:
ok cool - thanks !
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.