Home All Groups Group Topic Archive Search About

Help - Can Execute return a value?

Author
19 May 2006 5:48 PM
tvamsidhar
Hello

I'm relatively new to SQL Server/T-SQL and find myself stuck with this
problem:

I need to do something like this:

Declare @someValue NVarchar(100)
Declare @someFunction Varchar(100)
    --
    --  Assign value to @someValue from a Cursor
    --
    --
    --  Assign name of the function to @someFunction from a Cursor
    --
Declare @ret NVarchar(100)
    Execute 'Select @ret = ' + @someFunc + '(''' + @someValue + ''')'

I expect the last Execute statement to leave the return value from the
function in @ret.
What I get is
     Must declare the variable '@ret'.

I have also tried
     Execute sp_ExecuteSQL 'Select @ret = ' + @someFunc + '(''' +
@someValue + ''')'
with the same result.

Any help with making this work or other ways of doing this will be very
much appreciated!

TIA.
Vamsi.

Author
20 May 2006 12:40 AM
mesaalejandro
Vamsi,

Use sp_executesql.

Declare @ret NVarchar(100)
declare @sql nvarchar(4000)

set @sql = N'Select @ret = ' + @someFunc + '(''' + @someValue + ''')'

exec sp_executesql @sql, N'@ret NVarchar(100) output', @ret output

print @ret
go


The Curse and Blessings of Dynamic SQL
http://www.sommarskog.se/dynamic_sql.html


AMB
Author
20 May 2006 5:25 AM
tvamsidhar
Splendid!!
I still can't understand that one line of code, but, it worked
perfectly :-)
Thanks very much, AMB.

V.
Author
20 May 2006 7:11 PM
Erland Sommarskog
tvamsidhar (tvamsid***@gmail.com) writes:
> Splendid!!
> I still can't understand that one line of code, but, it worked
> perfectly :-)

For more details on sp_executesql and dynamic SQL in general, see
an article on my web site: http://www.sommarskog.se/dynamic_sql.html.

By the way, if you are new to T-SQL, dynamic SQL is probably not where
you should start.


--
Erland Sommarskog, SQL Server MVP, esq***@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
Author
20 May 2006 9:21 PM
tvamsidhar
Thanks Erland, I'll study the article! Its already in my Google
bookmarks :)

As for starting with dynamic SQL, I really don't have a choice :-) I
need to be able to run validations and formatting on type-less text
data that should be "interpreted" to be of datatypes defined in a
metadata repository (SQL Server tables) and satisfying validations
(reg. expressions, TSQL functions/SPs, etc) specified in the same
repository.

Running these on the app. server turned out to be way too inefficient
and cumbursome; hence the dynamic SQL. And although I'm more
experienced with PL/SQL, the powers that be insist on using SQL Server

I thank you for the input.

V.

AddThis Social Bookmark Button