Thursday, March 29, 2012

Can I INSERT INTO a temp tbl twice in one stored procedure

In my stored procedure I need to select some data columns and insert them into a #temp tbl and then select the same data columns again using a different from and put them into the same #temp tbl. It sounds like a union, can I union into a #temp tbl?

Any help here is appreciated.

You should be able to insert into the temp table twice, or use a union to just do one insert. Have you actually tried and got an error? If so can you post the error you got.|||The error in my stored procedure is:

There is already an object named '#temp_UN' in the database.

I'm trying to do something like this:

SELECT ClinetID, etc... INTO #temp_UN FROM ... WHERE...

SELECT ClinetID, etc... INTO #temp_UN FROM ... WHERE... (This select has a different FROM

SELECT ... FROM tblClient INNER JOIN tblClient.ClientID = #temp_UN.ClientID WHERE...

if

object_id('tempdb..#temp_UN','U')isnotnull

drop

table #temp_UNGifts|||

For your second insert into the temp table you should be able to use the 'Insert into .. select .. ' syntax

Something like this:

SELECT ClinetID, etc... INTO #temp_UN FROM ... WHERE...

INSERT INTO #temp_UN SELECT ClinetID, etc...FROM ... WHERE... (This select has a different FROM)

SELECT ... FROM tblClient INNER JOIN tblClient.ClientID = #temp_UN.ClientID WHERE...

HTH

|||

Thank you Steve, it looks like it was the order of things.

No comments:

Post a Comment