本例调用存储过程的方法为:
设置SqlCommand.Comand为CommandType.StoredProcedure,并使用DataReader呼叫存储过程。
如下边调用Northwind数据库中的“Ten Most Expensive Products”存储过程代码:
using System.Data;
using System.Data.SqlClient;
namespace SqlStoredProcedure
{
class Program
{
static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection(
@"Data Source=scott;Initial Catalog=northwind;Persist Security Info=True;User ID=sa;Password=sa123");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
//命令类型为存储过程
thisCommand.CommandType = CommandType.StoredProcedure;
//存储过程名称
thisCommand.CommandText = "Ten Most Expensive Products";
//执行存储过程
SqlDataReader thisReader = thisCommand.ExecuteReader();
//显示结果
while(thisReader.Read())
{
Console.WriteLine("\t{0}\t{1}", thisReader["TenMostExpensiveProducts"], thisReader["UnitPrice"]);
}
thisReader.Close();
thisConnection.Close();
Console.ReadLine();
}
}
using System.Data.SqlClient;
namespace SqlStoredProcedure
{
class Program
{
static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection(
@"Data Source=scott;Initial Catalog=northwind;Persist Security Info=True;User ID=sa;Password=sa123");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
//命令类型为存储过程
thisCommand.CommandType = CommandType.StoredProcedure;
//存储过程名称
thisCommand.CommandText = "Ten Most Expensive Products";
//执行存储过程
SqlDataReader thisReader = thisCommand.ExecuteReader();
//显示结果
while(thisReader.Read())
{
Console.WriteLine("\t{0}\t{1}", thisReader["TenMostExpensiveProducts"], thisReader["UnitPrice"]);
}
thisReader.Close();
thisConnection.Close();
Console.ReadLine();
}
}