1創建:使用VS2005的“存儲過程”模板創建;
2.部署:通過VS2005部署自動在SQLServer中創建存儲過程;
3.使用:在C#中使用命令對象調用存儲過程。
創建存儲過程:
GetProduct.cs:
using System; using System.Data; using System.Data.SqlClIEnt; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; public partial class StoredProcedures { [Microsoft.SqlServer.Server.SqlProcedure] public static void GetProduct(int id) { //使用調用該存儲過程的客戶端打開的連接 SqlConnection conn = new SqlConnection("Context Connection=true"); conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "Select ProductID, ProductName, CategoryID, Quantity FROM Products Where ProductID = @ID"; cmd.Parameters.Add("@ID", SqlDbType.Int, 0); cmd.Parameters["@ID"].Value = id; SqlDataReader reader = cmd.ExecuteReader(); SqlPipe pipe = SqlContext.Pipe; //將讀取器返回給客戶端 pipe.Send(reader); } }
測試存儲過程:
TestProc.cs:
using System; using System.Collections.Generic; using System.Text; using System.Data.SqlClIEnt; using System.Data; namespace Magci.Test.SQLServer.TestProc { class Program { static void Main(string[] args) { string source = @"server=.\sqlexpress; database=MGC; trusted_connection=true"; using (SqlConnection conn = new SqlConnection(source)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "GetProduct"; cmd.CommandType = CommandType.StoredProcedure; SqlParameter param = new SqlParameter("@id", 1); cmd.Parameters.Add(param); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { Console.WriteLine("Name: {0}, CategoryID: {1}, Quantity: {2}", reader["ProductName"], reader["CategoryID"], reader["Quantity"]); } reader.Close(); } conn.Close(); } Console.ReadLine(); } } }