欢迎使用CSDN-markdown编辑器

来源:互联网 发布:淘宝 天猫购物券 编辑:程序博客网 时间:2024/05/22 14:54

C#调用存储过程

怎样在C#中调用存储过程
1、没有参数没有返回值
2、有参数没有返回值
3、有参数有返回值

下面就这几种情况分别举例:
1、没有参数没有返回值 象这种情况最简单。

    USE Northwind        AS             SELECT * FROM products    GO    /// <summary>  ///        c#代码 方法1      /// </summary>
    SqlConnection conn = new SqlConnection();        //  SqlConnection  ==> sql连接    conn.ConnectionString = strConn;        //  ConnectionString  ==> 连接字符    SqlCommand comm = new SqlCommand("EXEC novaluenoparameter", conn);    comm.ExecuteNonQuery();          //  SqlCommand  ==>  sql命令        //  novaluenoparameter  ==>  存储过程名称        //  ExecuteNonQuery  ==>  执行非查询
情况2、有参数没有返回值   存储过程(带参数,没有返回值)
    CREATE PROC novaluebeparameter      @i int ,       @productname varchar(20)      AS        SELECT TOP @i * FROM products where productname = @productname    GO    /// <summary>       ///C#代码:调用带参数没有返回值的存储过程      /// </summary> 
    SqlConnection conn = new SqlConnection();      conn.ConnectionString = strConn;      conn.Open();    SqlCommand comm = new SqlCommand("novaluebeparameter", conn);                                    comm.CommandType = CommandType.StoredProcedure;        //  CommandType ==> 命令类型        //  StoredProcedure==> 存储过程    comm.Parameters.Add(new SqlParameter("@i",SqlDbType.Int));        //  Parameters ==> 参数        //  SqlDbType  ==>数据库类型    comm.Parameters.Add(new SqlParameter("@productname",SqlDbType.varchar,20));    comm.Parameters["@i"].Value=3;    comm.Parameters["@productname"].value = "Tofu"    comm.ExecuteNonQuery();      conn.Close();  
情况3、带参数,有返回值(返回一个值,这里说下,有返回一个值的,有返回一个数据集的。)   存储过程(带参数,没有返回值)
    CREATE PROC novaluebeparameter      @i int ,      @j int,       @sum int output       AS          SET @sum = @i + @j         RETURN @sum      GO    
0 0