Groups | Blog | Home
all groups > sql server (microsoft) > august 2005 >

sql server (microsoft) : sp_executesql


Bert
8/16/2005 10:16:27 AM
Hi, i've some problems with sp_executesql.
I want to store some queries in a table(-field) together with a description in another field.
With a 'select top 1' I tried to get a result, which succeeded.
Next I wanted to execute the result (which is a query).
This is what I can't get working.

Example:
declare @qry1 as nvarchar(100)
set @qry1 = 'select top 1 queryfield from myqueries'
execute sp_executesql @qry1
--so far no problem

--now I want to store the previous result (being a query) in a variable
--so I can execute it as a query again...
declare @result_of_qry1 as nvarchar(100)
select @result_of_qry1 = execute sp_executesql @qry1


Is something like this possible at all?
Are there workarounds?

TIA
Bert
David Portas
8/17/2005 12:33:20 AM
You can insert a result set into a table rather than a variable:

INSERT INTO table_name (...)
EXEC sp_executesql ...

You can also return individual scalar values from sp_executesql using OUTPUT
parameters. See the article below for examples.

Read the following about dynamic SQL to understand why we usually avoid it.
Then decide if you want to continue with this approach.
http://www.sommarskog.se/dynamic_sql.html

--
David Portas
SQL Server MVP
--

AddThis Social Bookmark Button