将datetime作为变量传递给aspx页面中的存储过程

时间:2011-06-14 21:22:43

标签: asp.net sql datetime variables stored-procedures

我有以下代码,我试图将datetime作为变量传递给存储过程。我尝试过几种不同的东西但没有运气。任何关于将日期传递给“@LVDate”的想法,以及传递给“@LVTime”的时间

   string connectionString = "server=abc;database=abc;uid=abc;pwd=1234";
   SqlConnection mySqlConnection = new SqlConnection(connectionString);
   string procedureString = "LV_Insert";
   SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
   mySqlCommand.CommandText = procedureString;
   mySqlCommand.CommandType = CommandType.StoredProcedure;
   mySqlCommand.Parameters.Add("@LVDate", SqlDbType.DateTime).Value = DateTime.Now;
   mySqlCommand.Parameters.Add("@LVTime", SqlDbType.DateTime).Value = DateTime.Now;
   mySqlConnection.Open();
   mySqlCommand.ExecuteNonQuery();
   SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
   mySqlDataAdapter.SelectCommand = mySqlCommand;
   mySqlConnection.Close();

另外,我需要让它们通过以下格式:

{0:MM/dd/yyyy},{0:HH:mm:ss}

2 个答案:

答案 0 :(得分:1)

你得到什么样的错误?可能是DateTime.Now的格式不正确,存储过程需要。使用String.Format;

String.Format("{0:MM/dd/yyyy", DateTime.Now);
String.Format("{0:HH:mm:ss", DateTime.Now);

答案 1 :(得分:1)

 string connectionString = "server=abc;database=abc;uid=abc;pwd=1234";
   SqlConnection mySqlConnection = new SqlConnection(connectionString);
   string procedureString = "LV_Insert";
   SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
   mySqlCommand.CommandText = procedureString;
   mySqlCommand.CommandType = CommandType.StoredProcedure;
   mySqlCommand.Parameters.Add( new SqlParameter("@LVDate", DateTime.Now));
   mySqlCommand.Parameters.Add(new SqlParameter("@LVTime", DateTime.Now));
   mySqlConnection.Open();
   mySqlCommand.ExecuteNonQuery();
   SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
   mySqlDataAdapter.SelectCommand = mySqlCommand;
   mySqlConnection.Close();