假設我們已經建立一個預存程序如下(四個輸入參數、一個輸出參數,執行查詢,並回傳查詢筆數):-- Create store procedureCREATE PROCEDURE usp_ComplexQuery @CustomerID nchar(5), @CompanyName nvarchar(40), @City nvarchar (15), @Country nvarchar(15), @STR nvarchar(1024) OUTPUTAS /*.....procedure content.....*/ SELECT * FROM Customers RETURN @@rowcountGO我們可以撰寫下列程式碼來執行預存程序並處理參數:public class NorthwindAdapter { private SqlConnection m_Connection = new SqlConnection(Properties.Settings.Default.NorthwindConStr); private string _SqlStr; private int _ReturnValue; public string SqlStr { get { return this._SqlStr; } set { this._SqlStr = value; } } public int ReturnValue { get { return this._ReturnValue; } set { this._ReturnValue = value; } } public DataTable usp_ComplexQuery(string customerid, string customername, string city, string country) { string cmdstr = @"usp_ComplexQuery"; using (SqlDataAdapter da = new SqlDataAdapter(cmdstr, m_Connection)) { da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5).Value = customerid; da.SelectCommand.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40).Value = customername; da.SelectCommand.Parameters.Add("@City", SqlDbType.NVarChar, 15).Value = city; da.SelectCommand.Parameters.Add("@Country", SqlDbType.NVarChar, 15).Value = country; da.SelectCommand.Parameters.Add("@STR", SqlDbType.NVarChar, 1024).Direction = ParameterDirection.Output; da.SelectCommand.Parameters.Add("@ReturnValue", SqlDbType.Int).Direction = ParameterDirection.ReturnValue; DataTable dt = new DataTable(); da.Fill(dt); this.SqlStr = da.SelectCommand.Parameters["@STR"].Value.ToString(); this.ReturnValue = Convert.ToInt32(da.SelectCommand.Parameters["@ReturnValue"].Value); return dt; } }}
標籤: ADO.NET
Post a Comment
較新的文章 較舊的文章 首頁