Today, I have provided an article showing you how to use a return value with a Stored Procedure 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. If we insert a duplicate record in the table then execution of a stored procedure will return a status value. If we insert a record into the table which is not duplicates. The successful execution of a stored procedure will return 0. Let's take a look at a practical example. The example is developed in SQL Server 2012 using the SQL Server Management Studio.
Return Value in Stored Procedure
Return values can be used within stored procedures to provide the stored procedure execution status to the calling program. You can create your own parameters that can be passed back to the calling program. By default, the successful execution of a stored procedure will return 0.
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 UsingExistsstoredprocedure
- (
- @UserName VARCHAR(100)
- )
- AS
- DECLARE @ResultValue int
- BEGIN TRAN
- IF EXISTS
- (
- SELECT * FROM UserTable
- WHERE UserName = @UserName
- )
- BEGIN
- SET @ResultValue = -5
- END
- ELSE
- BEGIN
- INSERT INTO UserTable
- (
- UserName
- )
- VALUES
- (
- @UserName
- )
- set @ResultValue = @@ERROR
- END
- IF @ResultValue <> 0
- BEGIN
- ROLLBACK TRAN
- END
- ELSE
- BEGIN
- COMMIT TRAN
- END
- RETURN @ResultValue





Gowtham RajamanickamPosted Apr 1, 2015, 1:08 AM
bokmrked
Ismail Hakki SenPosted Sep 7, 2014, 7:37 AM
Good advice. Bookmarked.