Today, I have provided an article showing you how to display the return value from a Stored Procedure output parameter in a Query Window in SQL Server 2012. In this article, we create a Stored Procedure to avoid duplicate record insertion in the SQL Server database prior to insertion into the database. You can determine the value of the out parameter corresponding to the different condition as an out parameter. Let's have a look at a practical example. The example is developed in SQL Server 2012 using the SQL Server Management Studio.
Output Keyword
The Output keyword to the parameters in the Stored Procedures can return the values of the parameters to the calling program. Now create a table named UserTable with the columns UserID, UserName. Set the identity property=true for UserID. The table looks as in the following:
Now create a Stored Procedure:
- Create PROCEDURE [dbo].[ExecuteProcedurewithOUTParameter]
- (
- @UserName VARCHAR(100),
- @ResultValue int out
- )
- AS
- BEGIN TRAN
- IF EXISTS
- (
- SELECT * FROM Testoutvalue
- WHERE Name = @UserName
- )
- BEGIN
- SET @ResultValue = -5
- END
- ELSE
- BEGIN
- INSERT INTO Testoutvalue
- (
- Name
- )
- VALUES
- (
- @UserName
- )
- set @ResultValue = 1
- END
- IF @@ERROR <> 0
- BEGIN
- ROLLBACK TRAN
- END
- ELSE
- BEGIN
- COMMIT TRAN
- END
- Select @ResultValue
In the preceding Stored Procedure we declare an output parameter ResultValue. "If exists" is used to check the insertion record whether it belongs to the table or not. If the inserted record is already in the table then set the return status @ResultValue= -5 and the inserted record is not in the table by default; the successful execution of a Stored Procedure will return 1.
Now hit F5 to execute the Stored Procedure:
Now insert a value into the table using the Stored Procedure and check the result of executing the Stored Procedure with the output parameter values as follows:
- DECLARE @Outputparam VARCHAR(20);
- Exec ExecuteProcedurewithOUTParameter 'ROhatashkumar', @Outputparam output
Now execute the Stored Procedure. Now press F5 to run the Stored Procedure.
Every time you insert new records it will return the same above output. Now using a select statement to select the record from the table.
Now, we can execute the procedure with duplicate values to check how the RETURN statement works:
- DECLARE @Outputparam VARCHAR(20);
- Exec ExecuteProcedurewithOUTParameter 'Rahul',@Outputparam output
Output