Execute stored procedure with an Output parameter? - sql-server

I have a stored procedure that I am trying to test. I am trying to test it through SQL Management Studio. In order to run this test I enter ...
exec my_stored_procedure 'param1Value', 'param2Value'
The final parameter is an output parameter. However, I do not know how to test a stored procedure with output parameters.
How do I run a stored procedure with an output parameter?

The easy way is to right-click on the procedure in Sql Server Management Studio (SSMS), select 'Execute stored procedure..." and add values for the input parameters as prompted. SSMS will then generate the code to run the procedure in a new query window, and execute it for you. You can study the generated code to see how it is done.

you can do this :
declare #rowCount int
exec yourStoredProcedureName #outputparameterspOf = #rowCount output

Return val from procedure
ALTER PROCEDURE testme #input VARCHAR(10),
#output VARCHAR(20) output
AS
BEGIN
IF #input >= '1'
BEGIN
SET #output = 'i am back';
RETURN;
END
END
DECLARE #get VARCHAR(20);
EXEC testme
'1',
#get output
SELECT #get

Check this, where the first two parameters are input parameters and the 3rd is an Output parameter in the Procedure definition.
DECLARE #PK_Code INT;
EXEC USP_Validate_Login 'ID', 'PWD', #PK_Code OUTPUT
SELECT #PK_Code

Procedure Example :
Create Procedure [dbo].[test]
#Name varchar(100),
#ID int Output
As
Begin
SELECT #ID = UserID from tbl_UserMaster where Name = #Name
Return;
END
How to call this procedure
Declare #ID int
EXECUTE [dbo].[test] 'Abhishek',#ID OUTPUT
PRINT #ID

From https://learn.microsoft.com/en-US/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql (originally http://support.microsoft.com/kb/262499)
CREATE PROCEDURE Myproc
#parm varchar(10),
**#parm1OUT varchar(30) OUTPUT**,
**#parm2OUT varchar(30) OUTPUT**
AS
SELECT #parm1OUT='parm 1' + #parm
SELECT #parm2OUT='parm 2' + #parm
GO
DECLARE #SQLString NVARCHAR(500)
DECLARE #ParmDefinition NVARCHAR(500)
DECLARE #parmIN VARCHAR(10)
DECLARE #parmRET1 VARCHAR(30)
DECLARE #parmRET2 VARCHAR(30)
SET #parmIN=' returned'
SET #SQLString=N'EXEC Myproc #parm,
#parm1OUT OUTPUT, #parm2OUT OUTPUT'
SET #ParmDefinition=N'#parm varchar(10),
#parm1OUT varchar(30) OUTPUT,
#parm2OUT varchar(30) OUTPUT'
EXECUTE sp_executesql
#SQLString,
#ParmDefinition,
#parm=#parmIN,
#parm1OUT=#parmRET1 OUTPUT,#parm2OUT=#parmRET2 OUTPUT
SELECT #parmRET1 AS "parameter 1", #parmRET2 AS "parameter 2"
GO
DROP PROCEDURE Myproc

First, declare the output variable:
DECLARE #MyOutputParameter INT;
Then, execute the stored procedure, and you can do it without parameter's names, like this:
EXEC my_stored_procedure 'param1Value', #MyOutputParameter OUTPUT
or with parameter's names:
EXEC my_stored_procedure #param1 = 'param1Value', #myoutput = #MyOutputParameter OUTPUT
And finally, you can see the output result by doing a SELECT:
SELECT #MyOutputParameter

With this query you can execute any stored procedure (with or without an output parameter):
DECLARE #temp varchar(100)
EXEC my_sp
#parameter1 = 1,
#parameter2 = 2,
#parameter3 = #temp output,
#parameter4 = 3,
#parameter5 = 4
PRINT #temp
Here the datatype of #temp should be the same as #parameter3 within your Stored Procedure.

How about this? It's extremely simplified:
The SPROC below has an output parameter of #ParentProductID
We want to select the value of the output of #ParentProductID into #MyParentProductID which is declared below.
Here's the Code:
declare #MyParentProductID int
exec p_CheckSplitProduct #ProductId = 4077, #ParentProductID = #MyParentProductID output
select #MyParentProductID

Try this; it's working fine for the multiple output parameter:
CREATE PROCEDURE [endicia].[credentialLookup]
#accountNumber varchar(20),
#login varchar(20) output,
#password varchar(50) output
AS
BEGIN
SET NOCOUNT ON;
SELECT top 1 #login = [carrierLogin],#password = [carrierPassword]
FROM [carrier_account] where carrierLogin = #accountNumber
order by clientId, id
END
Try for the result:
SELECT *FROM [carrier_account]
DECLARE #login varchar(20),#password varchar(50)
exec [endicia].[credentialLookup] '588251',#login OUTPUT,#password OUTPUT
SELECT 'login'=#login,'password'=#password

CREATE PROCEDURE DBO.MY_STORED_PROCEDURE
(#PARAM1VALUE INT,
#PARAM2VALUE INT,
#OUTPARAM VARCHAR(20) OUT)
AS
BEGIN
SELECT * FROM DBO.PARAMTABLENAME WHERE PARAM1VALUE=#PARAM1VALUE
END
DECLARE #OUTPARAM2 VARCHAR(20)
EXEC DBO.MY_STORED_PROCEDURE 1,#OUTPARAM2 OUT
PRINT #OUTPARAM2

Here is the stored procedure
create procedure sp1
(
#id as int,
#name as nvarchar(20) out
)
as
begin
select #name=name from employee where id=#id
end
And here is the way to execute the procedure
declare #name1 nvarchar(10)
exec sp1 1,#name1 out
print #name1

Please check below example to get output variable value by executing a stored procedure.
DECLARE #return_value int,
#Ouput1 int,
#Ouput2 int,
#Ouput3 int
EXEC #return_value = 'Your Sp Name'
#Param1 = value1,
#Ouput1 = #Ouput1 OUTPUT,
#Ouput2 = #Ouput2 OUTPUT,
#Ouput3 = #Ouput3 OUTPUT
SELECT #Ouput1 as N'#Ouput1',
#Ouput2 as N'#Ouput2',
#Ouput3 as N'#Ouput3'

Here is the definition of the stored_proc:
create proc product(#a int,#b int)
as
return #a * #b
And, this is executing it from Python:
conn = pyodbc.connect('...')
cursor = conn.cursor()
sql = """
SET NOCOUNT ON
declare #r float
exec #r=dbo.product 5,4
select #r
"""
result = cursor.execute(sql)
print (result.fetchall())

Related

Create temp table from dynamic SQL with parameters

Here is my issue. I need to create a temp table after executing dynamic SQL and passing params as follows
CREATE PROCEDURE SP1
#param1 varchar(50),
#param2 varchar(50)
AS
BEGIN
DECLARE #PDef varchar(300)
DECLARE #sql varchar(300)
DECLARE #localparam1 varchar(300)
DECLARE #localparam2 varchar(300)
SET #localparam1 = ....
SET #localparam2 = ....
SET #PDef = '#param1 varchar(50), #localparam1 varchar(300)'
SET #sql = 'SELECT * FROM TABL1 WHERE COL1 = #param1, COL2 in (#localparam1)'
EXEC sp_Executesql #sql, #PDef,
#param1 = #param1, #localparam1 = #localparam1
The above works. How do I get the results into a temp table?
I tried
CREATE TABLE #T1 (col1 varchar(50), col2 varchar(50) )
INSERT INTO #T1
EXECUTE #sql -- didn't work
INSERT INTO #T1
EXECUTE (#sql, #PDef, #param1 = #param1, #localparam1 = #localparam1) -- didn't work either
EDIT: Had Looked at the following samples while using EXECUTE
Dynamic SQL results into temp table in SQL Stored procedure and hence used EXECUTE
The accepted answer was:
INSERT into #T1 execute ('execute ' + #SQLString )
omit the 'execute' if the sql string is something other than a procedure
Now see the comments to that accepted answer that question that accepted answer :-)
You've removed sp_executesql from your query for some reason. You can't called sys.sp_executesql if you don't tell SQL Server to:
INSERT INTO #T1
EXECUTE sys.sp_executesql #sql;
INSERT INTO #T1
EXECUTE sys.sp_executesql #sql,
#PDef,
#param1 = #param1,
#localparam1 = #localparam1;

How to insert a field of a procedure result in a variable?

I have a procedure dbo.pX that returns a table with 1 field named id and an INT in it, that can be equal to 0, or another positive integer. I need to insert this id in a variable inside a procedure named dbo.pY, to verify if the id is greater than 0.
Procedure dbo.pX:
CREATE PROCEDURE dbo.pX
#param1 VARCHAR(30)
AS
DECLARE #id INT;
-- Some code to change the #id
SELECT #id AS 'id';
GO
What I tried to do in dbo.pY:
CREATE PROCEDURE dbo.pY
#param1 VARCHAR(30)
AS
DECLARE #ret INT;
SET #ret = (EXECUTE dbo.pX 'something');
IF ( #ret > 0 ) BEGIN
-- Some code that uses #ret
END
GO
Any tips or hints to help me find a way to solve it?
Obs: I can't change the procedure dbo.pX.
As I know the fields that the procedure was bringing me, and I couldn't change that procedure, I solve it like this:
CREATE PROCEDURE dbo.pY
#param1 VARCHAR(30)
AS
-- insert the procedure table inside a temporary table
DECLARE #temp TABLE (id INT);
INSERT INTO #temp EXECUTE dbo.pX 'something';
-- insert id that the table brings in a variable
DECLARE #ret INT;
SELECT #ret = id FROM #temp;
IF ( #ret > 0 ) BEGIN
-- Some code that uses #ret
END
GO
Problem solved :)

T-SQL Stored Procedure returned value into variable

I have a simple stored procedure on MS SQL 2012 Express that returns a result doing something like :
DECLARE #value INT;
SELECT #value;
Meanwhile I am trying to call this stored procedure doing something like
DECLARE #result INT;
EXEC #result = SpFoo .....
However the value I get on #result from the SpFoois 0.
How can I get the real value returned from the Stored Procedure?
Thanks
First declare #Value as output parameter in your called sp
CREATE PROCEDURE spCallee
#Value INT Output
AS
BEGIN
set #Value = 1
END
GO
Get result like this in caller sp
CREATE PROCEDURE spCaller
AS
BEGIN
declare #Result as int = 0
EXEC spCallee #Value = #Result Output
Select #Result
END
GO
The only way I know is to put result to the table and then get it from it:
DECLARE #tmp TABLE (Result int)
DECLARE #res int
INSERT INTO #tmp
EXECUTE [Procedure]...
SELECT #res = Result
FROM #tmp

How to pass output parameter to a Stored Procedure?

I have written a stored procedure with the following format:
ALTER PROCEDURE usp_data_migration
(#sourceDatabase varchar(50),
#sourceTable varchar(50),
#targetDatabase varchar(50),
#targetTable varchar(50),
#finaloutput varchar(max) output)
AS
BEGIN
----Set of SQL Blocks
END
Then, I am executing the procedure:
DECLARE #finaloutput1 varchar(300)
EXEC usp_data_migration 'Yousuf', 'emp', '[City Branch]', 'emp_tgt', #finaloutput1 output
SELECT #finaloutput1
By executing this way I don't proper output.
When I execute this way:
DECLARE #finaloutput1 varchar(300)
EXEC usp_data_migration #sourceDatabase = 'Yousuf',
#sourceTable = 'emp',
#targetDatabase = '[City Branch]',
#targetTable = 'emp_tgt',
#finaloutput1 output
SELECT #finaloutput1
I get an error message saying:
Msg 119, Level 15, State 1, Line 41
Must pass parameter number 5 and subsequent parameters as '#name = value'. After the form '#name = value' has been used, all subsequent parameters must be passed in the form '#name = value'.
And if I removed my output parameter and execute the procedure, I get my desired output but I am not able to get my result as an output.
EXEC usp_data_migration #sourceDatabase = 'Yousuf',
#sourceTable = 'emp',
#targetDatabase = '[City Branch]',
#targetTable = 'emp_tgt'
What should I do?
Thanks in advance.
The error message is self-explanatory - you should name all of your parameters.
DECLARE #finaloutput1 varchar(300);
EXEC dbo.usp_data_migration -- always use schema prefix
#sourceDatabase = 'Yousuf',
#sourceTable = 'emp',
#targetDatabase = '[City Branch]',
#targetTable = 'emp_tgt',
#finaloutput = #finaloutput1 OUTPUT;
SELECT #finaloutput1;
You have to Select like this
Example 1
create procedure p1
(
#id INT,
#name varchar(20) OUTPUT,
#company varchar(20) OUTPUT
)
AS
BEGIN
Set #name = 'name'
Set #company = 'company'
select #name , #company from table1 where id = #id;
END
GO
Example 2
CREATE PROCEDURE Myproc
#parm varchar(10),
#parm1OUT varchar(30) OUTPUT,
#parm2OUT varchar(30) OUTPUT
AS
SELECT #parm1OUT='parm 1' + #parm
SELECT #parm2OUT='parm 2' + #parm
GO
DECLARE #SQLString NVARCHAR(500)
DECLARE #ParmDefinition NVARCHAR(500)
DECLARE #parmIN VARCHAR(10)
DECLARE #parmRET1 VARCHAR(30)
DECLARE #parmRET2 VARCHAR(30)
SET #parmIN=' returned'
SET #SQLString=N'EXEC Myproc #parm,
#parm1OUT OUTPUT, #parm2OUT OUTPUT'
SET #ParmDefinition=N'#parm varchar(10),
#parm1OUT varchar(30) OUTPUT,
#parm2OUT varchar(30) OUTPUT'
EXECUTE sp_executesql
#SQLString,
#ParmDefinition,
#parm=#parmIN,
#parm1OUT=#parmRET1 OUTPUT,#parm2OUT=#parmRET2 OUTPUT
SELECT #parmRET1 AS "parameter 1", #parmRET2 AS "parameter 2"
go
drop procedure Myproc
Please refer more here
Simple Example:
create procedure proc2 #var int out,#var2 varchar(10) out
as
begin
set #var=(select max(id) from customer);
set #var2=(select name from customer where id=#var);
end
declare #maxid int;
declare #maxname varchar(10);
exec proc2 #maxid out,#maxname out;
select #maxid,#maxname;

Output Parameter Not Returned

Why does this script return a pair of nulls? I'm using SQL Server 2008, script run in MSSMS.
CREATE PROCEDURE proc_Test
(
#Input int,
#Out1 int OUTPUT,
#Out2 varchar(10) OUTPUT
)
AS
BEGIN
SET NOCOUNT OFF
SET #Out1 = 100 + #Input
SET #Out2 = 'result=' + CONVERT(varchar,#Out1)
RETURN
END
GO
DECLARE #Out1 int, #Out2 varchar(10)
exec proc_Test #Input=1, #Out1=#Out1, #Out2=#Out2
select #Out1, #Out2
You need to specify vars as output:
DECLARE #Out1 int, #Out2 varchar(10)
exec proc_Test #Input = 1, #Out1 = #Out1 output, #Out2 = #Out2 output
select #Out1, #Out2
As a small matter of style try not to name the vars that receive the results the same as the parameter variables; it gets too confusing.

Resources