1:无参数的存储过程

建立存储过程如下:

Uselibrarydatabase   //指定所要建的存储过程的数据库

go

Createprocedure p_book    //新建存储过程p_book

As

select*from bookwhere条形码='ts100008' //SQL语句集合

执行编译之后在数据库的可编程性节点里面的存储过程可以看得到!

在VS2005里面新建一个控制台程序,新建一个方法如下:


public void nopara()
     {
           SqlConnection con =newSqlConnection("server=.;database=librarydatabase;userid=sa;pwd=;");    //数据库连接字段
           SqlCommand com =newSqlCommand("p_book", con);   //调用存储过程
            com.CommandType =CommandType.StoredProcedure;  //指定执行的类型
            con.Open();  //打开数据库连接
           try
            {
               SqlDataReader sdr = com.ExecuteReader(); //执行存储过程
               while (sdr.Read()) 
                {
                   Console.WriteLine(sdr[2].ToString());  //sdr方括号里面的数值就是返回记录的方列,这里是显示第三列的值,从0开始算
                }
                con.Close(); //关闭数据库连接
               Console.ReadKey();
            }
           catch
            {
               Console.WriteLine("something iswrong");
               Console.ReadKey();
            }
 }

此时客户端就直接调用该方法即可!

 

 

2:有参数的存储过程

调用有参数的存储过程其实并不复杂,和类中方法参数的传递相似,只不过存储过程里面的参数前必须要有“@”作用!

建立存储过程如下:

Use librarydatabase   //指定所要建的存储过程的数据库

go

Createprocedure lib_reader

@name nvarchar(20) //定义一个nvarchar型的参数,注意,用“@”修饰

as

select*from readerwhere姓名=@name   //完整的SQL语句,引用该参数

执行编译。

再新建一个方法如下:


public  void haspara()
{
           SqlConnection con =newSqlConnection("server=.;database=librarydatabase;userid=sa;pwd=;");  //数据库连接字段
           SqlDataAdapter sda =newSqlDataAdapter("lib_reader", con);  //调用存储过程,和前一个例子不同,这里用SqlDataAdapter,省去了打开数据库连接!          
           //con.Open();  此句可以省去,因为执行SqlDataAdapter已经打开了连接了
           SqlParameter para0 =newSqlParameter("@name","张三");  //给参数赋值,注意参数格式
           sda.SelectCommand.Parameters.Add(para0);   //添加参数值
            sda.SelectCommand.CommandType =CommandType.StoredProcedure;  //指定执行类型为存储过程
           try
            {
                DataSet ds =newDataSet();
                sda.Fill(ds,"table"); 
               foreach (DataRow therowinds.Tables["table"].Rows)
                {
                    Addr = therow["家庭地址"].ToString().Trim();//读取返回记录的相应字段,Addr必须先声明为string型才可以使用
                    Tel = therow["电话"].ToString().Trim();//读取返回记录的相应字段
                }
               Console.WriteLine("家庭地址是:{0},所在系:{1}", password, quanxian);
                con.Close();  
               Console.ReadKey();                            
            }
           catch
            {
               Console.WriteLine("something iswrong");
                con.Close();  
            }
  }