简体   繁体   中英

Pass datetime to stored procedure

Using sql server 2012. I'm having a hard time passing a date parameter to the stored procedure. The column's datatype in the table is datetime .

alter procedure savedate()
(
  @StartDate datetime
)

The text from the source textbox is 2014-09-18.

The below code will give an error - string not recognized as valid datetime

SqlParams[0] = new SqlParameter("@StartDate", SqlDbType.DateTime);
SqlParams[0].Value = Convert.ToDateTime(txtStartDate.Text.Trim());//error here

And this will say - Failed to convert parameter value from string to datetime

SqlParams[0] = new SqlParameter("@StartDate", SqlDbType.DateTime);
SqlParams[0].Value = txtStartDate.Text.Trim();
SqlHelper.ExecuteDataset(conn, CommandType.StoredProcedure, "savedate",
                         SqlParams); //error here

I'm reading about culture variants, but dont know how to fix this.

Use DateTime.ParseExact to get your string converted to a datetime then pass the datetime

string test = "2014-09-18";
DateTime dt = DateTime.ParseExact(test, "yyyy-MM-dd", CultureInfo.InvariantCulture);
SqlParams[0] = new SqlParameter("@StartDate", SqlDbType.DateTime);
SqlParams[0].Value = dt;

If your input comes from a user typed value, then it is probably better to use DateTime.TryParseExact to verify the input without getting an exception.

if(!DateTime.TryParseExact(test, "yyyy-MM-dd", 
             CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
    MessageBox.Show("Type a date in the format yyyy-MM-dd");
    return;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM