Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Declare Input-Output Parameters In SQL Server Stored Procedure/Function?

In Oracle,

We can declare an input-output parameters (not just input or output) like the following:

Create Or Replace Procedure USERTEST.SimpleInOutProcedure(
    p_InputInt Int,
    p_OutputInt out Int,
    p_InputOutputInt in out Int
) AS
BEGIN
    p_OutputInt := p_InputInt + 1;
    p_InputOutputInt := p_InputOutputInt + p_InputOutputInt;
END;

However, as I try to declare such in SQL Server, the script would not compile:

create procedure SimpleInOutProcedure 
    @p_InputInt int, @p_OutputInt int input output
As
Begin
    Select * from TestTableCommonA;
End

The word "input" is not expected, thus not blue-colored in the SQL Server Management Studio:

enter image description here

What's wrong with my script, how to declare input-output parameters in SQL Server Stored Procedure/Function?

I want to do this because I need to create "equivalent" reader for SQL Server DB which previously was created for Oracle DB and has the reader for in/out parameters.

like image 731
Ian Avatar asked Mar 06 '18 11:03

Ian


2 Answers

If you declare a parameter as OUTPUT, it acts as Both Input and OUTPUT

CREATE PROCEDURE SimpleInOutProcedure 
(
    @p_InputInt  INT,
    @p_OutputInt INT OUTPUT
)
AS
BEGIN
    SELECT 
       @p_OutputInt = @p_OutputInt
END
GO

DECLARE @p_OutputInt int = 4
EXEC SimpleInOutProcedure @p_InputInt = 1, @p_OutputInt = @p_OutputInt OUTPUT
SELECT @p_OutputInt
like image 53
Jayasurya Satheesh Avatar answered Nov 09 '22 23:11

Jayasurya Satheesh


This is sample code for SQL Input & Output parameter.

CREATE PROCEDURE [dbo].[sample_Insert]
@name varchar(500),
@entryby int,
@RetVal INT = 0 OUT

AS

SET NOCOUNT ON



INSERT INTO dbo.Master
        ( name ,
          entry_date ,
          entry_by
        )
VALUES  ( @name , -- service_name - varchar(1000)
          dbo.GetActDate() , -- entry_date - datetime
          @entryby  -- entry_by - int
        )




IF @@ERROR =  0
BEGIN
SET @RetVal = 1 -- 1 IS FOR SUCCESSFULLY EXECUTED
End
ELSE
BEGIN
SET @RetVal = 0 -- 0 WHEN AN ERROR HAS OCCURED
End

 set ANSI_NULLS ON
 set QUOTED_IDENTIFIER ON
like image 33
ravi polara Avatar answered Nov 09 '22 21:11

ravi polara