定义一个根据存储过程名称和存储过程参数数组,执行对应的存储过程的方法。用SqlParameter[]代替存储过程需要的参数。这样就不用为每一个存储过程写一个方法了
1、首先定义一个ExcuteProcedure()方法,执行存储过程,并返回第一行第一列的结果
public static object ExcuteProcedure(string proName, SqlParameter[] paramt) { using (SqlCommand command = new SqlCommand()) { object returnInfo = string.Empty; command.Connection = conn; //定义的SqlConnention对象 command.CommandText = proName; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddRange(paramt); command.Connection.Open(); try { returnInfo = command.ExecuteScalar(); } catch { //return "False"; } finally { command.Connection.Close(); } return returnInfo; } }
2、再定义一个方法,执行存储过程,并返回结果集
public static DataSet ExcuteProcedureDS(string proName, SqlParameter[] paramt) { using (SqlCommand command = new SqlCommand()) { command.Connection = conn; command.CommandText = proName; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddRange(paramt); command.Connection.Open(); using (SqlDataAdapter sda = new SqlDataAdapter()) { DataSet ds = new DataSet(); sda.SelectCommand = command; try { sda.Fill(ds); return ds; } catch { return null; } finally { conn.Close(); ds.Dispose(); } } } }
3、然后就可以传递存储过程名称和SqlParameter[]数组,调用这两个方法执行对应存储过程。
比如有这样的一个存储过程:该存储过程有5个参数。
USE [mydb] GO /****** Object: StoredProcedure [dbo].[ProUpUserList] Script Date: 03/30/2014 12:30:55 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- 作者: <毛泽西> -- 英文名: <tracine> -- 创建日期: <2014/3/30> -- 描叙: <更新用户表> -- ============================================= ALTER proc [dbo].[ProUpUserList] ( ), ), ), ), ) ) as declare @count int select @count=COUNT(*) from UserList where UserName=@UserName begin select '用户不存在' as 'result' end else begin begin tran Up declare @DeptID int,@RoleID int select @DeptID=DepartID from DepartmentList where DepartmentName=@DeptName select @RoleID=RoleID from RoleList where RoleName=@RoleName update UserList set Name=@Name,UserName=@UserName,DepartID=@DeptID,RoleID=@RoleID,UserPassword=@UserPassword where UserName=@UserName begin rollback tran Up select '修改失败' as 'result' end else begin commit tran Up select '修改成功' as 'result' end end
调用执行存储过程代码:
SqlParameter[] parameter = new SqlParameter[] { //存储过程5个参数名称以及参数类型 new SqlParameter("), new SqlParameter("), new SqlParameter("), new SqlParameter("), new SqlParameter("), }; //存储过程5个参数的值 parameter].Value = name; parameter].Value = userName; parameter].Value = name; parameter].Value = departName; parameter].Value = roleName; //调用执行存储过程的方法 string result = SQLdbHelper.ExcuteProcedure("ProUpUserList", parameter).ToString();
只是这种方法不适合应用与WebService,因为它不支持SqlParameter类型,无法进行参数传递