-1

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

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

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

我准备好了我的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
4

2 回答 2

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();
于 2013-09-10T12:00:07.587 回答
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 调用节省大量时间。

于 2013-09-10T16:12:53.057 回答