StoredProcedure in C# is a precompiled and optimized collection of SQL statements that can be executed on a database. It is used to encapsulate a set of SQL statements that performs a particular task. The stored procedure can return output parameters as well as return values.
Here are some examples of Stored Procedure in C#:
Example 1: Stored Procedure with Input and Output Parameters
CREATE PROCEDURE [dbo].[spGetEmployeeByID] @EmployeeID INT, @FullName NVARCHAR(50) OUTPUT, @Designation NVARCHAR(50) OUTPUT AS BEGIN SELECT @FullName = FullName, @Designation = Designation FROM Employee WHERE EmployeeID = @EmployeeID END
Example 2: Stored Procedure with Return Value
CREATE PROCEDURE [dbo].[spGetEmployeeCount] AS BEGIN DECLARE @Count INT
SELECT @Count = COUNT(*) FROM Employee
RETURN @Count END
In both the examples, the package library used is System.Data.SqlClient which is a namespace in the .NET framework to access SQL server databases.
To use Stored Procedure in C#, first, we need to connect to the database using SqlConnection object. Then, we can call the stored procedure using SqlCommand object and pass input parameters and retrieve output values if needed.
Example 1 Code:
using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand cmd = new SqlCommand("spGetEmployeeByID", connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@EmployeeID", 1); cmd.Parameters.Add("@FullName", SqlDbType.NVarChar, 50).Direction = ParameterDirection.Output; cmd.Parameters.Add("@Designation", SqlDbType.NVarChar, 50).Direction = ParameterDirection.Output;
using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand cmd = new SqlCommand("spGetEmployeeCount", connection)) { cmd.CommandType = CommandType.StoredProcedure;
int count = (int)cmd.ExecuteScalar(); } }
C# (CSharp) StoredProcedure - 60 examples found. These are the top rated real world C# (CSharp) examples of StoredProcedure extracted from open source projects. You can rate examples to help us improve the quality of examples.