2011-03-03 47 views
1

您可以使用带有单词的文本框并将其传递给SQL存储过程?我想使用存储过程,但我试图创建一个搜索页面,所以我想我正在试图找出如何保留存储过程,但将文本框的值传递给存储过程。SQL存储过程值来自页面

+0

一些更多的细节会很好。语言? WinForm的/ Web窗体? – 2011-03-03 16:18:07

回答

3

是的,很容易,这里是一个完整的article举例

下面是相关的代码片段:

类别名称可以从你的控件的Text属性进行设置。

static void GetSalesByCategory(string connectionString, 
    string categoryName) 
{ 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    { 
     // Create the command and set its properties. 
     SqlCommand command = new SqlCommand(); 
     command.Connection = connection; 
     command.CommandText = "SalesByCategory"; 
     command.CommandType = CommandType.StoredProcedure; 

     // Add the input parameter and set its properties. 
     // HERE IS What you need. 
     SqlParameter parameter = new SqlParameter(); 
     parameter.ParameterName = "@CategoryName"; 
     parameter.SqlDbType = SqlDbType.NVarChar; 
     parameter.Direction = ParameterDirection.Input; 
     parameter.Value = categoryName; 

     // Add the parameter to the Parameters collection. 
     command.Parameters.Add(parameter); 

     // Open the connection and execute the reader. 
     connection.Open(); 
     SqlDataReader reader = command.ExecuteReader(); 

     if (reader.HasRows) 
     { 
      while (reader.Read()) 
      { 
       Console.WriteLine("{0}: {1:C}", reader[0], reader[1]); 
      } 
     } 
     else 
     { 
      Console.WriteLine("No rows found."); 
     } 
     reader.Close(); 
    } 
} 
+0

值得一提的是,有些东西(称为它们 - 工具?库?框架?)可以让这个过程更容易一些,例如, Linq To SQL,Enterprise Library,nHibernate,Entity Framework等 – 2011-03-03 17:53:16

+0

当然,我刚刚认为OP是一个比较新的东西,俗话说他必须飞行的人必须先学会走路等,即学习大多数抽象的东西,然后抽象出 – kd7 2011-03-03 17:55:49