日期:2014-05-19  浏览次数:20836 次

c#调用sql存储过程
我只想在c#调用sql存储过程,我有三个存储过程的名字叫tj,js,sc   (即添加一列,计算数据,删除一列)  
请问如何使用代码调用它们!最好写我解释!!
谢谢大家!

------解决方案--------------------
dataSet.Reset();
//执行存储过程
command = new SqlCommand( "GetDeliverItem ", connection);
//说明命令要执行的是存储过程
command.CommandType = CommandType.StoredProcedure;
//向存储过程中传递参数
command.Parameters.Add(new SqlParameter( "@SampCode ", SqlDbType.VarChar, 30));
command.Parameters.Add(new SqlParameter( "@DeptName ", SqlDbType.VarChar, 100));
command.UpdatedRowSource = UpdateRowSource.None;
command.Parameters[ "@SampCode "].Value = sampCode;
command.Parameters[ "@DeptName "].Value = combSelDeliver.Text.ToString();
//执行命令
dapt.SelectCommand = command;
dapt.SelectCommand.ExecuteNonQuery();
dapt.Fill(dataSet, "samp000 ");
dataView.Table = dataSet.Tables[ "samp000 "];
dataGridView1.DataSource = dataSet.Tables[ "samp000 "];

------解决方案--------------------
一、建立存储过程
以SQL Server200自带的用户数据库Northwin,建立存储过程
CREATE PROCEDURE [dbo].[protestc]
@ProductName varchar(50)= ' '
AS
if(@ProductName= ' ' Or @ProductName=null)
select top 10 * from Products
else
select * from Products where ProductName like '% '+@ProductName+ '% '
GO
//该过程很简单,就是让你输入一个值,然后数据将用该值对ProductName进行模糊查询;该值也可以为空,这时数据库返回表中所有一记录。
二、代码实现
//首先程序中有一个DataGrid,用来显示数据;有一个TextBox和一个Button,TextBox用来让用户输入查询关键字,按Button开始查询。查询的关键代码如下:
protected void btnSelect_Click(object sender, EventArgs e)
{
string name = this.tbName.Text.Trim();//这是用户在TextBox中输入的数据。
SqlConnection conn = new SqlConnection( "server=.;database=Northwind;uid=sa;pwd= 'x ' ");
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
sda.SelectCommand = new SqlCommand( "protestc ", conn);//调用存储过程
sda.SelectCommand.CommandType = CommandType.StoredProcedure;//这一句表示SqlDataAdapter调用执行的是一个存储过程。如果没有这一句,该存储过程将不会被执行。
sda.SelectCommand.Parameters.Add( "@ProductName ", SqlDbType.VarChar, 50);//向存储过程传入一个参数。
sda.SelectCommand.Parameters[ "@ProductName "].Value = name;
sda.Fill(ds, "proname ");//将数据填充至本地DataSet的proname表中。
conn.Close();
this.gvShow.DataSource = ds.Tables[ "proname "];
this.gvShow.DataBind();//数据绑定GridView
}

------解决方案--------------------
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand( "存储过程名 ",con);
cmd.CommandType= CommandType.StoredProcedure;
SqlParameter sp = new SqlParameter( "@存储过程的参数1 ",SqlDbType.VarChar,50);
sp.Value= "给参数1赋值 ";
cmd.Parameters.Add(sp);
sp =new SqlParameter( "@存储过程的参数2 ",SqlDbType.Int,8);
sp.Value=1;
cmd.Parameters.Add(sp);
//参数赋值完毕为止,然后执行绑定
------解决方案--------------------
try
{
openConnection();//打开连接
SqlDataAdapter myCommand = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "tj ";//存儲過程名字
cmd.Connection = conn;