Fork me on GitHub
.NET中调用存储过程(Output、Input)

带输入输出参数的存储过程

create procedure itemCodes

@itemName1 varchar(50),

@sizeName1 varchar(50),

@itemCode varchar(5) output

as

select @itemCode=itemmap.ItemCode from itemmap inner join item on itemmap.ItemCode=item.ItemCode where(item.ItemName1=@itemName1 and item.SizeName1=@sizeName1)

go

程序清单1

   static void ExecuteStoredProcedure(string itemName1,string sizeName1)

        {

            string strConn = "server=localhost;uid=sa;pwd=sa;database=PAT";

            SqlConnection conn = new SqlConnection(strConn);

            conn.Open();

            SqlCommand cmd = new SqlCommand("getItemCode", conn);

            cmd.CommandType = CommandType.StoredProcedure;

            //输入参数

            SqlParameter param1 = new SqlParameter("@itemName1", SqlDbType.VarChar, 50);

            param1.Value = itemName1;

            cmd.Parameters.Add(param1);

            //输入参数

            SqlParameter param2 = new SqlParameter("@sizeName1", SqlDbType.VarChar, 50);

            param2.Value = sizeName1;

            cmd.Parameters.Add(param2);

            //输出参数

            SqlParameter param = new SqlParameter("@itemCode", SqlDbType.VarChar, 50);

            param.Direction = ParameterDirection.Output;

            cmd.Parameters.Add(param);

            //执行存储过程

            cmd.ExecuteNonQuery();

            conn.Close();

            //输出值

            Console.WriteLine(param.Value);

        }

程序清单2

static void ExecuteProcedure()

        {

            string strConn = "server=localhost;uid=sa;pwd=sa;database=PAT";

            SqlConnection conn = new SqlConnection(strConn);

            conn.Open();

            SqlCommand cmd = new SqlCommand("getItemCode", conn);

            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter[] parameters =

            {

                new SqlParameter("@itemName1",SqlDbType.VarChar,50),

                new SqlParameter("@sizeName1",SqlDbType.VarChar,50),

                new SqlParameter("@itemCode",SqlDbType.VarChar,50)

            };

            parameters[0].Value = "Chai";

            parameters[1].Value = "500g";

            parameters[2].Direction = ParameterDirection.Output;

            foreach (var p in parameters)

            {

                cmd.Parameters.Add(p);

            }

            cmd.ExecuteNonQuery();

            conn.Close();

            //输出值

            Console.WriteLine(parameters[2].Value);

        }

 


       快速评论通道--您对本文的宝贵意见:
       
感谢您的鼓励和批评,它将是我进步的动力

posted on 2010-06-24 19:09  HackerVirus  阅读(389)  评论(1)    收藏  举报