0

I have a stored proc, SP1, which executes and does select on one table. Now i have the need to insert that data in another table. I dont want to duplicate the code so i thought of inserting the data returned by the SP1 in the temp table so i can do some processing on it and save it.

I tried INSERT INTO #tmp; exec dbo.Sp1; but it gives me an error saying Invalid object name '#tmp'.. Isnt there a way i can create this table dynamically? Is there a better solution to this problem?

1

3 Answers 3

1

The temp table has to exist before you can use insert into exec.

This is not such a draw back as it first seems as any changes to the procedure result set will likely brake your code.

Sign up to request clarification or add additional context in comments.

2 Comments

if my app uses one userid to connect to db, will that not create the problem as session will be shared to multiple users?
no each connection will have a separate session and therefore separate temporary tables even with the same userid. A single # will be local to a session, double hash ## will be global to all users.
0

first run this:

create proc MySelect as begin select 1 as myColumn1, 2 as mycolumn2 end 

and then this:

create table #tmp( col_1 int, col_2 int) insert into #tmp exec MySelect select * from #tmp 

Comments

0

If you have control over dbo.sp1 then the easiest way is to use a temp table. Declare the temp table in the parent proc and use it in the child proc (without declaring it).

The table will maintain scope through both and you wont have to worry about multiple users running it since temp tables are local.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.