将datetime传递给存储过程 [英] Pass datetime to stored procedure

查看:140
本文介绍了将datetime传递给存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用sql server 2012.我很难将date参数传递给存储过程。
表中的列数据类型是 datetime

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
)

源文本框中的文字是2014-09-18。

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

以下代码将给出一个错误 - 字符串未被识别为有效的datetime

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

这将说 - 无法将参数值从字符串转换为datetime

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

我正在阅读文化变体,但不知道如何解决这个问题。 / p>

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

推荐答案

使用 DateTime.ParseExact 将您的字符串转换为datetime,然后传递datetime

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;

如果您的输入来自用户输入的值,那么最好使用 DateTime.TryParseExact 验证输入而不会得到异常。

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

这篇关于将datetime传递给存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆