Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return two output parameters sp_executesql

I have dynamic query I want to get two output parameters from it I used the following code , but the output parameters return null

declare @query nvarchar(max);
declare @result int; 
declare @type int
declare @mainVarcharLength int; 

set @query = 'select   count(*) ,  Type_Code from Customers   WHERE Customers.Cust_Name =  ''CUSTOMER 99''  '
set @query = @query + '  and Cus_Is_Active = 1  Group BY   Type_Code';
select  @query

EXEC sp_executesql @query, N'@result int OUTPUT,  @type int OUTPUT', @result,  @type

select @result
select @type

How to solve that , and how to pass multiple output parameters

like image 724
AMH Avatar asked Nov 24 '11 12:11

AMH


People also ask

What does Sp_executesql return?

Return values are generally not used to "return" a result but to return success (0) or an error number (1-65K). The above all seem to indicate that sp_executesql does not return a value, which is not correct. sp_executesql will return 0 for success and any other number for failure.

What is the difference between Exec vs Sp_executesql?

EXEC : EXEC/Execute is used to execute any stored procedure or character string. Mostly it is used to execute the stored procedure. 2. SP_ExecuteSQL: SP_ExecuteSQL is used to execute ad-hoc SQL statements so that they can be executed as parameterized statements.

Can we use Sp_executesql in function?

It appears that you can't. You can execute extended stored procedure inside a function and, even though sp_executesql is an extended stored procedure (despite its name), it still generates the message "only functions and extended stored procedures can be executed within a function".


1 Answers

You need to state what is being allocated to the outputs;

set @query = 'select @result=count(*), @type=Type_Code from Customers ....'

then decorate the outputs with OUTPUT;

EXEC sp_executesql @query,   
    N'@result int OUTPUT, @type int OUTPUT',
    @result OUTPUT, 
    @type OUTPUT

(You could also pass ''CUSTOMER 99'' as an input)

like image 139
Alex K. Avatar answered Sep 25 '22 13:09

Alex K.