Groups | Blog | Home
all groups > sql server (microsoft) > june 2007 >

sql server (microsoft) : How to retrieve results from a dynamic SQL query


InvestorTrade
6/15/2007 1:41:58 PM
Hi,

I have a query that is formed dynamically, and I need to be able
store the result in a variable, and example of this would be:

BEGIN

DECLARE @myresult int
DECLARE @query = 'select count(*) from sysobjects'

SET @myresult = exec (@query)

END

I thought of using Global temporary tables (##) where I could store
the result, but I rather not.

Thank you for any help,

James.
Ed Murphy
6/15/2007 3:16:47 PM
[quoted text, click to view]

James.Shih.Neulion NO[at]SPAM gmail.com
6/18/2007 12:00:00 AM
[quoted text, click to view]

Yes, but how would a store procedure help? I need to store the result
of the query - keep in mind that there may be concurrent invocations
to the same query - also that I would like to save (if possible) the
operation cost.

Thank you,

James.
Will
6/18/2007 1:23:37 PM
[quoted text, click to view]

Have you considered creating a proper table into which you store the
results, together with the SPID for the current session? (i.e.
@@SPID). You'd then use the SPID at a later point to pull back 'this
sessions' results (remember to delete them at some point!).

Far from ideal, but a better approach than a global table, I fear!
Ed Murphy
6/18/2007 4:52:06 PM
[quoted text, click to view]

Because you can feed the output of the stored procedure into a
(non-global) temporary table. Quick example:

create procedure foo as
begin
select bar, baz from the_table
end

create table #foo (bar int, baz varchar(10))

insert into #foo exec foo

James.Shih.Neulion NO[at]SPAM gmail.com
6/19/2007 12:00:00 AM
[quoted text, click to view]

OK - Yes - I knew about the temporary table and already thought about
this too - but I don't want to use it - I think it might be cheaper to
use memory than creating a temp table in the drive - unless temp
tables are created in memory. Thank you for the suggestion, any other
way you may think of?
Ed Murphy
6/19/2007 8:29:00 AM
[quoted text, click to view]

This smells like premature optimization. How often will you be
doing this? How large will the output be? Anyway, SQL generally
AddThis Social Bookmark Button