Monday, March 26, 2012

Saving EXEC Result to a Variable ?

How can I save the EXEC Result to a Variable.
For example:
declare @.myString as varchar(50)
declare @.myValue as decimal(12,2)
set @.myString='Select ' + '10-5'
EXEC (@.myString)
Print @.myalue <-- Should print 5you can use sp_ExecuteSql. Check BOL for more info on this. or google it.
--
Av.
http://dotnetjunkies.com/WebLog/avnrao
http://www28.brinkster.com/avdotnet
"Luqman" <pearlsoft@.cyber.net.pk> wrote in message
news:uP38IDcDFHA.3340@.TK2MSFTNGP10.phx.gbl...
> How can I save the EXEC Result to a Variable.
> For example:
> declare @.myString as varchar(50)
> declare @.myValue as decimal(12,2)
> set @.myString='Select ' + '10-5'
> EXEC (@.myString)
> Print @.myalue <-- Should print 5
>
>
>|||You can also do this using either temp tables or a user-defined function:
CREATE FUNCTION udf_test( @.value1 DECIMAL( 12, 2 ), @.value2 DECIMAL( 12, 2 )
)
RETURNS DECIMAL( 12, 2 )
AS
BEGIN
DECLARE @.result DECIMAL( 12, 2 )
SET @.result = @.value1 - @.value2
RETURN @.result
END
GO
DECLARE @.myString VARCHAR(50)
DECLARE @.myValue DECIMAL( 12, 2 )
-- Temp table way
CREATE TABLE #result ( result DECIMAL( 12, 2 ) )
SET @.myString = 'INSERT INTO #result SELECT ' + '10-5'
EXEC( @.myString )
SELECT * FROM #result
DROP TABLE #result
-- User defined function way (Make sure you set the database owner dbo to
whatever you need)
SET @.myValue = dbo.udf_test( 10, 5 )
PRINT @.myValue
DROP FUNCTION udf_test
GO
"Luqman" wrote:

> How can I save the EXEC Result to a Variable.
> For example:
> declare @.myString as varchar(50)
> declare @.myValue as decimal(12,2)
> set @.myString='Select ' + '10-5'
> EXEC (@.myString)
> Print @.myalue <-- Should print 5
>
>
>
>sql

No comments:

Post a Comment