x
login about faq Site discussion (meta-askssc)

Get results into table from dynamic tsql

How can we insert the dynamic query result into temporary table without defined the structure of that temporary table.

more ▼

asked Sep 03 '12 at 06:39 AM in Default

Parthasarathy gravatar image

Parthasarathy
60 1 2 7

I tried Something like that: insert into @table EXEC(@sql)

Without define the @table..how can solve this problem

Sep 04 '12 at 05:25 AM Parthasarathy

See my answer. But please be aware of the global temporary table concurrency issues that I mention as well.

Sep 04 '12 at 06:23 AM Magnus Ahlkvist
(comments are locked)
10|1200 characters needed characters left

2 answers: sort voted first

To generate a temporary table dynamically without specificng the structure up front, use the SELECT INTO syntax

select col1, col2, col3
into #YourTempTable
from AnotherTable

The datatypes will be determined by the base datatypes in the source tables (or expressions if an explicit convert is done)

more ▼

answered Sep 03 '12 at 07:29 AM

Kev Riley gravatar image

Kev Riley ♦♦
46.1k 38 43 69

(comments are locked)
10|1200 characters needed characters left

When you say "dynamic query results", I assume you mean the results from a string containing sql, that you execute with EXECUTE('select * from someTable') If that's the case, you have only one option that I can think of: Use a global temporary table.

Like this:

EXECUTE('SELECT * INTO ##t FROM someTable')

Then you can use the global temporary table in your code. Like this:

SELECT * FROM ##t

The problem with this solution is that the temporary table you create is global. It will cause problems in a multi-user environment, if this is run by two users at the (more or less) same time the SELECT INTO will fail since the table already exists.

more ▼

answered Sep 03 '12 at 11:12 AM

Magnus Ahlkvist gravatar image

Magnus Ahlkvist
13.7k 13 17 30

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments



Facebook logo Follow Ask SSC on Facebook
Find Ask SSC on Google+
linkedin logo Find us on LinkedIn

Topics:

x35
x25

asked: Sep 03 '12 at 06:39 AM

Seen: 501 times

Last Updated: Sep 04 '12 at 06:23 AM

Copyright © 2002-2012 Simple Talk Publishing. All Rights Reserved. If you have any queries, please contact the site administrators.
Ask SQL Server Central is a community service provided by Red Gate.