1

I'm writing a stored procedure. I have a string which contains an sql query. For example:

DECLARE @sql nvarchar(max)
SET @sql = (N'SELECT pkOrderID FROM Orders') 

(Just to note: this isn't what the select statement looks like. This is just an example of what I mean) I then want to execute the string and put the result in a temporary table E.g. #tempTable. I know EXEC(@sql) exists but not sure if it will do me any good in this situation. The other twist is that I do not know the names of all the columns in the returned @sql so the temp table #tempTable needs to be created dyanmically based off the return from @sql. Thanks for any help.

2 Answers 2

2

I think you could use SELECT INTO to do what you want but it would mean updating your string:

DECLARE @sql nvarchar(max)
SET @sql = (N'SELECT frompkOrderID INTO #tmporders FROM Orders') 

then you should be able to run EXEC @sql to create the table

more information about SELECT INTO here : http://msdn.microsoft.com/en-au/library/ms188029.aspx

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

2 Comments

Is there a way for me to do this without creating the structure of tempTable and dynamically having it create the columns based off whats returned from @sql
Select Into will create the table based on the result, assuming it doesn't already exist. Will add a reference to my answer
1

There is no simple way to do this. The problem with @JanR's solution is that the #tmporders table will be out of scope to the script that calls your stored procedure (ie It will produce an error like "Invalid object name '#rtmporders'"

One alternative is to use a global temp table (eg ##tmporders).

So your SP might look like this:

CREATE PROCEDURE TestSP 
AS
BEGIN
  SELECT pkOrderID  INTO ##tmporders FROM Orders
END
GO

And the calling script might be like:

EXEC TestSP
SELECT * FROM ##temporders

3 Comments

ya I just ran into the out of scope issue. Let me try this out
When I try and drop the table at the end of the sp with DROP TABLE ##tempTable. It says cannot drop because it either doesn't exist or I dont have permission. I'm guessing it thinks it doesn't exist but it does because it properly executed the string statement...
Global temp tables (##table) are dropped automatically when the session that created the table ends, and whenever any other TSQL referencing that table has finished.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.