日期:2014-05-18  浏览次数:20726 次

c#中使用存储过程

首先创建存储过程,sql语句如下所示:

USE [YCYFFJKXT]
GO
/****** 对象:  StoredProcedure [dbo].[Login_UserCount]    脚本日期: 07/17/2012 14:53:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[Login_UserCount]
@ZH VARCHAR(20),
@MM varchar(50),
@Rowcount INT OUTPUT
AS
BEGIN
 SELECT * FROM YHXX WHERE ZH=@ZH and MM=@MM
 SET  @Rowcount=@@ROWCOUNT
END

c#中调用

SqlConnection conn_Local = new SqlConnection();
            conn_Local.ConnectionString = "server=.;database=YCYFFJKXT;user id=sa;password=sa";
            try
            {
                conn_Local.Open();
                SqlCommand cmd_Count = new SqlCommand("Login_UserCount",conn_Local);
                cmd_Count.CommandType = CommandType.StoredProcedure;

                //添加输入查询参数、赋予值
                cmd_Count.Parameters.Add("@ZH", SqlDbType.VarChar);
                cmd_Count.Parameters.Add("@MM",SqlDbType.VarChar);
                cmd_Count.Parameters["@ZH"].Value = "A";
                cmd_Count.Parameters["@MM"].Value = "B";

                //添加输出参数
                cmd_Count.Parameters.Add("@Rowcount", SqlDbType.Int);
                cmd_Count.Parameters["@Rowcount"].Direction = ParameterDirection.Output;

                cmd_Count.ExecuteNonQuery();

                Console.WriteLine("受影响的行数是"+cmd_Count.Parameters["@Rowcount"].Value.ToString());


            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                conn_Local.Close();
            }
            Console.ReadLine();