调用存储过程

时间:2013-09-10 10:53:52

标签: c# sql-server sql-server-2008-r2

我是C#的新手我需要调用SP并从C#返回表值。

我将当前datetime(@currentdate)作为输入参数传递给存储过程。那么如何在C#方法中传递它?

请帮我编写一个C#方法来调用该SP并返回值

我准备好了。 sp将返回表中的最新更新记录。

我在我的C#代码

中使用过它
string _Num = null;
SqlConnection sqlConnection1 = new SqlConnection("Data Source=localhost;Initial Catalog=ReferenceDB;Persist Security Info=True;Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand();
Int32 rowsAffected;
Object returnValue;

cmd.CommandText = "Number";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@CurrentDate", DateTime.Now);
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

rowsAffected = cmd.ExecuteNonQuery();

returnValue = cmd.ExecuteScalar();
if (returnValue != null)
    _Num = returnValue.ToString();

return _Num

2 个答案:

答案 0 :(得分:0)

Write his code in that method

    SqlConnection con = new SqlConnection("coonectionstring");
    SqlCommand cmd = new SqlCommand();
     SqlCommand cmd = new SqlCommand("Your sp",con);   
    cmd.CommandType = CommandType.StoredProcedure;
    //input parameters
         cmd.Parameters.Add(new SqlParameter("@currentdate",SqlDbType.DateTime,"currentdate"));
       int i=command.ExecuteNonQuery();

答案 1 :(得分:0)

如果您要在C#代码中使用多个sp,我建议使用以下内容:

public static DataTable GetSQLValues(string currentDate)
    {
        SqlParameter[] sqlParams = 
        { 
            new SqlParameter("@currentDate", currentDate)
        };

        return DBHelper.GetTable("MSSQLSPNAME", sqlParams);
    }

对于需要获取表格信息的每个实例,请使用以上内容。

GetTable看起来像这样:

    static SqlConnection _conn;
    static string _connStr = ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["primaryConnStr"]].ToString();
    static SqlCommand _cmd;
    static SqlDataAdapter _dataAdapter = new SqlDataAdapter();

    public static DataTable GetTable(string sProcName, SqlParameter[] sqlParams)
    {
        using (_conn = new SqlConnection(_connStr))
        {
            _cmd = new SqlCommand(sProcName, _conn);

            _conn.Open();
            _cmd.CommandType = CommandType.StoredProcedure;

            if (sqlParams != null)
            {
                _cmd.Parameters.AddRange(sqlParams);
            }

            _dataAdapter = new SqlDataAdapter(_cmd);

            var results = new DataTable();

            _dataAdapter.Fill(results);
            _conn.Close();

            return results;
        }
    }

从C#中为每个sp调用节省大量时间。