在 ADO.NET 中调用存储过程






2.56/5 (21投票s)
2006 年 8 月 30 日
2分钟阅读

389190
执行 SQL Server 存储过程以及如何检索返回参数的介绍
引言
存储过程是一组 SQL 命令,它们被编译并存储在数据库中。 每次执行 SQL 命令时,都会对该命令进行解析、优化,然后执行。 每次运行查询时都对命令进行解析和优化是非常昂贵的。 为了解决这个问题,我们有一组命令统称为存储过程,它们已经被解析和优化,并且在每次调用它们时都会被执行。 本文介绍了如何通过 Ado.net 调用存储过程以及如何处理已调用存储过程的输出参数。
首先,创建一个 SqlConnection 类的对象,该类在 System.Data.SqlClient 命名空间中可用。 必须提供连接字符串作为参数,其中包括数据源名称、数据库名称和身份验证凭据。 使用 Open() 方法打开连接。
SqlConnection con = new SqlConnection("Data Source= ; initial catalog= Northwind ; User Id= ; Password= '");
con.open();
在 Northwind 数据库的 Region 表上创建以下存储过程,该过程接受两个参数并且没有任何输出参数。
CREATE PROCEDURE RegionUpdate (@RegionID INTEGER, @RegionDescription NCHAR(50)) AS SET NOCOUNT OFF UPDATE Region SET RegionDescription = @RegionDescription
使用参数创建一个 SqlCommand 对象,该参数是待执行存储过程的名称,以及将命令发送到其以供执行的连接对象 con。
SqlCommand command = new SqlCommand("RegionUpdate",con);
将命令对象的 CommandType 属性更改为存储过程。
command.CommandType = CommandType.StoredProcedure;
使用 Parameters 集合和 SqlParameter 类将参数添加到命令对象。
command.Parameters.Add(new SqlParameter("@RegionID",SqlDbType.Int,0,"RegionID")); command.Parameters.Add(new SqlParameter("@RegionDescription",SqlDbType.NChar,50,"RegionDescription"));
使用参数的 Value 属性指定参数的值
command.Parameters[0].Value=4;
command.Parameters[1].Value="SouthEast";
使用 ExecuteNonQuery 方法执行存储过程,该方法返回存储过程影响的行数。
int i=command.ExecuteNonQuery();
现在让我们看看如何执行具有输出参数的存储过程,以及如何使用输出参数访问结果。
创建以下具有一个输出参数的存储过程。
ALTER PROCEDURE RegionFind(@RegionDescription NCHAR(50) OUTPUT, @RegionID INTEGER )AS SELECT @RegionDescription =RegionDescription from Region where RegionID=@RegionID
上述存储过程接受 regionID 作为输入参数,并找到 RegionID 输入的 RegionDescription,并将其作为输出参数返回。
SqlCommand command1 = new SqlCommand("RegionFind",con);
command1.CommandType = CommandType.StoredProcedure;
将参数添加到 command1
command1.Parameters.Add(new SqlParameter ("@RegionDescription",SqlDbType.NChar ,50,ParameterDirection.Output,false,0,50,"RegionDescription",DataRowVersion.Default,null)); command1.Parameters.Add(new SqlParameter("@RegionID" , SqlDbType.Int, 0 , "RegionID" ));
注意参数 RegionDescription 被添加,ParameterDirection 为 Ouput。
指定输入参数 RegionID 的值。
command1.Parameters["@RegionID"].Value = 4;
将 SqlCommand 对象的 UpdatedRowSource 属性分配给 UpdateRowSource.OutputParameters,以指示将通过输出参数从该存储过程返回数据。
command1.UpdatedRowSource = UpdateRowSource.OutputParameters;
调用存储过程并使用参数的 value 属性访问 RegionID 4 的 RegionDescription。
command1.ExecuteNonQuery();
string newRegionDescription =(string) command1.Parameters["@RegionDescription"].Value;
关闭 sql 连接。
con.Close();
以同样的方式,您可以通过定义适当的参数并使用 ExecuteReader() 执行命令来调用返回一组行的存储过程,该方法用于遍历该命令返回的记录。