Pass datetime to stored procedure

旧时模样 提交于 2019-12-11 20:13:50

问题


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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/25886290/pass-datetime-to-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!