SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE dbo.sp_test
-- Add the parameters for the stored procedure here
@IdFoo int
AS
BEGIN
SELECT
*
FROM
Foo
WHERE
IdFoo = @IdFoo
END
GO SET ANSI_NULLS ON
GO
SET
QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE dbo.sp_test
-- Add the
parameters for the stored procedure here
@IdFoo
int
AS
BEGIN
SELECT
*
FROM
Foo
WHERE
IdFoo =
@IdFoo
END
GO
Este procedimiento recibe como parametro el entero @IdFoo, y busca en la tabla Foo, un registro que tenga el campo IdFoo igual al parametro de entrada @IdFoo. Para llamar este procedimiento de almacenado desde nuestro código tan sólo debemos hacer lo siguiente
public void ExecuteStoreProcedure(int idFoo)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
connection.Open();
command.Connection = connection;
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "sp_test";
command.CommandTimeout = 10;
command.Parameters.AddWithValue("@IdFoo", idFoo);
SqlDataReader reader = command.ExecuteReader();
}
}
} public void
ExecuteStoreProcedure(int idFoo)
{
using (SqlConnection connection = new
SqlConnection(connectionString))
{
using (SqlCommand command = new
SqlCommand())
{
connection.Open();
command.Connection =
connection;
command.CommandType =
System.Data.CommandType.StoredProcedure;
command.CommandText =
"sp_test";
command.CommandTimeout =
10;
command.Parameters.AddWithValue("@IdFoo", idFoo);
SqlDataReader reader
= command.ExecuteReader();
}
}
}
Como vemos es muy fácil, creamos una conexión, y un comando. A este comando le decimos que ejecutará el procedimiento sp_test y le pasamos el parametro idFoo como @IdFoo. El resultado de la consulta se guarda en un SqlDataReader. Ahora podremos recorrer este SqlDataReader para devolver algún dato o pasar la información a un objeto de negocio.
La principales ventajes de los procedimientos almacenados son:
- La velocidad de la consulta es mayor.
- Toda la logica de acceso a datos se encuentra en la base de datos.