C#调用存储过程 之返回值与输出参数的区别与用法实例

本文介绍如何使用 C# 在 Visual Studio 中调用 SQL Server 2008 的存储过程,并展示如何通过 SqlCommand 对象传递参数及接收返回值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


首先定义存储过程如下:(sqlserver 2008)

use studb2008 
go 
create procedure proc_test 
@num int=-1 output 
as 
  set @num=10 --输出参数 
  return 2  --返回值 
  go

 


 

然后在vs中写如下c#代码:

namespace StoreProcedureTest 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        {

            string s = @"Data Source=.\sql2008express;Initial Catalog=studb2008;User ID=sa;Password=sa"; 
            SqlConnection con = new SqlConnection(s); 
            SqlCommand command = new SqlCommand(); 
            command.Connection = con; 
            command.CommandText = "proc_test"; //proc_test为存储过程的名字 
           command.CommandType = CommandType.StoredProcedure; //设置执行的类型 
            SqlParameter para = new SqlParameter("@a",SqlDbType.Int);//任意定义一个变量,来接收返回值参数 
            para.Direction = ParameterDirection.ReturnValue;   //注意这里1 表示接收返回值 
            command.Parameters.Add(para); 
            SqlParameter para2 = new SqlParameter("@num", SqlDbType.Int); //第二个变量来接收存储过程的输出参数 
            para2.Direction = ParameterDirection.Output;   //注意这里2 表示接收输出值 
          command.Parameters.Add(para2); 
            con.Open(); 
            command.ExecuteNonQuery(); 
            int n = (int)command.Parameters["@a"].Value; 
            int n2 = (int)command.Parameters["@num"].Value; 
            Console.WriteLine(“n:”+n+":n2="+n2); //分别输出返回值和输出参数的值。分别是2和10 
            Console.ReadLine(); 
            con.Close();

        } 
    } 
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值