How do i call a stored procedure with parameters from c# code behind
I have created a stored procedure shown below ,how will i call this from c# code behind to get the result and results are stored in dataset.
USE [Test]
GO
/****** Object: StoredProcedure [dbo].[tesproc] Script Date: 09/01/2010 13:00:54 ******/
SET ANSI_N开发者_运维技巧ULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[tesproc]
-- Add the parameters for the stored procedure here
@a float, @b float, @c float,@d int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
select Id, Name1,ZipCode,StreetName,StreetNumber,State1,Lat,Lng, ( 6371 * ACOS( COS( (@a/@b) ) * COS( (Lat/@b) ) * COS( ( Lng/@b ) - (@c/@b) ) + SIN( @a/@b ) * SIN( Lat/@b ) ) ) as distance from business_details where ( 6371 * ACOS( COS( (@a/@b) ) * COS( (Lat/@b) ) * COS( ( Lng/@b ) - (@c/@b) ) + SIN( @a/@b ) * SIN( Lat/@b ) ) )<@d
END
If i execute this stored procedure in sql server its working fine with this following call
exec dbo.tesproc 12.9216667 ,57.2958,77.591667,1
using (SqlConnection conn = new SqlConnection("connection string goes here"))
using (SqlCommand comm = new SqlCommand("tesproc", conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.AddWithValue("@a", 0.1);
// etc
conn.Open();
using (SqlDataReader reader = comm.ExecuteReader())
{
while (reader.Read())
{
int id = reader.GetInt32(reader.GetOrdinal("id"));
// etc
}
}
}
There are lots of comprehensive samples on the internet:
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson04.aspx
My code sample is just demonstrating what it might look like - it was written straight in the editor so may not work on its own.
Look into SqlConnection
and SqlCommand
.
精彩评论