怎样在C#中调用存储过程?

来源:互联网 发布:淘宝投诉第三方服务商 编辑:程序博客网 时间:2024/05/01 03:54

             废话不说,直接切入主题。先来说下存储过程的几种情况:

                                                                                                                    1、没有参数没有返回值 

                                                                                                                    2、有参数没有返回值

                                                                                                                    3、有参数有返回值

 

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

  1. 存储过程
  2. USE Northwind
  3. CREATE PROC novaluenoparameter
  4. AS
  5.   SELECT * FROM products
  6. GO

            

  1. /// <summary>
  2. /// c#代码 方法1
  3. /// </summary>
  4. SqlConnection conn = new SqlConnection();
  5. conn.ConnectionString = strConn;
  6. conn.Open();
  7. SqlCommand comm = new SqlCommand("EXEC novaluenoparameter", conn);
  8. comm.ExecuteNonQuery();
  9. conn.Close();

     

    情况2、有参数没有返回值

    1. 存储过程(带参数,没有返回值)
    2. CREATE PROC novaluebeparameter
    3. @i int ,
    4. @productname varchar(20)
    5. AS
    6.    SELECT TOP @i * FROM products where productname = @productname
    7. GO
    1. /// <summary>
    2. /// C#代码:调用带参数没有返回值的存储过程
    3. /// </summary>
    4. SqlConnection conn = new SqlConnection();
    5. conn.ConnectionString = strConn;
    6. conn.Open();
    7. SqlCommand comm = new SqlCommand("novaluebeparameter", conn); //“novaluebeparameter”是存储过程名
    8. comm.CommandType = CommandType.StoredProcedure;
    9. comm.Parameters.Add(new SqlParameter("@i",SqlDbType.Int));
    10. comm.Parameters.Add(new SqlParameter("@productname",SqlDbType.varchar,20));
    11. comm.Parameters["@i"].Value=3;
    12. comm.Parameters["@productname"].value = "Tofu"
    13. comm.ExecuteNonQuery();
    14. conn.Close();

    3、带参数,有返回值(返回一个值,这里说下,有返回一个值的,有返回一个数据集的。)

    1. 存储过程(带参数,没有返回值)
    2. CREATE PROC novaluebeparameter
    3. @i int ,
    4. @j int,
    5. @sum int output
    6. AS
    7.    SET @sum = @i + @j
    8.    RETURN @sum
    9. GO

     

    原创粉丝点击