Returning Data From a Stored Procedure

Tuesday, January 10, 2012

tags SQL

SQL Procedures are also very good for scenarios where you want to send input parameters, process information, and return data back for displaying or reporting purposes. In this example, we'll take a look at how to send two parameters, process the parameters, and send back the results for further processing. This example will add two integers and return the sum of the two integers.

Example



USE [databaseName]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[add2numbers]
@num1 int,
@num2 int

AS
BEGIN
SET NOCOUNT ON;

DECLARE @total int

SET @total = @num1 + @num2
return @total
END

GO


Execute the Stored Procedure



/* In a SQL Analyzer window, use the following lines of code to execute the stored procedure. */

declare @result int
exec @result= add2numbers @num1=2,@num2=5
select @result as [Sum]


Results




Sum
7

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

SQL Cookbook Head First SQL: Your Brain on SQL A Learners Guide