先就簡單的沒有參數的情況簡要的介紹:
假設存儲過程如下: CREATE PROC SelectAll
AS
SELECT * FROM StudentInf
則此sp的調用如下:
SqlCommand selectCMD = new SqlCommand(“SelectAll”, conn);
//conn 為SqlConnection
selectCMD.CommandType = CommandType.StoredProcedure;
如果需要將結果集加到某個DataAdapter上,則可如下:
SqlDataAdapter stuDA = new SqlDataAdapter();
stuDa.SelectCommand = selectCMD;
如果有參數:create proc andSelect
@StudentId varchar(10),
@StudentName varchar(10),
As
Select * from StudentInf where StudentId = @StudentId and StudentName = @StudentName
則參數可以如下添加:
selectCMD.Parameters.Add(“@StudentId”, SqlDbType.NVarChar, 10);
selectCMD.Parameters.Add(“@StudentName”, SqlDbType.NvarChar, 10);
如果只有一個參數,也可以這樣賦值:
SqlParameters onePara = selectCMD.Parameters.Add(“@StudentId”, SqlDbType.NVarChar, 10);
onePara.Value = “ a string ”