简体   繁体   English

来自ASP.NET的SQL Server存储过程中的日期参数

[英]Date parameter in SQL Server stored procedure from ASP.NET

I've written an SQL Server stored procedure that, amongst other things, accepts a date parameter: 我编写了一个SQL Server存储过程,该存储过程除其他外还接受date参数:

CREATE PROCEDURE data.addScore
    ... (some parameters),
    @testDate date
AS

On an ASP.NET page I have a textbox with a Calender Extender control (from the AJAX Toolkit) that allows the user to select a date; 在ASP.NET页面上,我有一个带有Calender Extender控件的文本框(来自AJAX Toolkit),该控件允许用户选择日期。 the date is stored in the textbox in the format DD/MM/YYYY . 日期以DD/MM/YYYY格式存储在文本框中。 I have some code that is supposed to execute the stored procedure with the parameters, using the date value from the textbox: 我有一些代码应该使用文本框中的日期值来使用参数执行存储过程:

cmd.Parameters["@testDate"].Value = Convert.ToDateTime(((TextBox)li.FindControl("date")).Text);

I know I can definitely get to the textbox's value using ((TextBox)li.FindControl("date")).Text , but for the life of me I can't get it into a format that doesn't throw up one of a few errors, mainly 'Input string was not in the correct format'. 我知道我绝对可以使用((TextBox)li.FindControl("date")).Text来获取文本框的值,但是对于我一生来说,我无法将其转换为不会抛出以下内容之一的格式:一些错误,主要是“输入字符串的格式不正确”。

When I run the stored procedure directly on the server I usually bind the parameter like @testDate = 'YYYYMMDD' . 当我直接在服务器上运行存储过程时,通常会绑定@testDate = 'YYYYMMDD'类的参数。

I would suggest you don't store anything in the textbox using regional, ambiguous formats like dd/mm/yyyy. 我建议您不要使用诸如dd / mm / yyyy之类的区域性模棱两可的格式在文本框中存储任何内容。 If you use an unambiguous format like YYYYMMDD, you're not going to have any issues. 如果您使用YYYYMMDD这样的明确格式,则不会有任何问题。 And if users are picking from a calendar control or something, it should be easy to separate the date you present to them from the date you pass to the database. 而且,如果用户正在从日历控件或其他控件中进行选择,那么将提供给他们的日期与传递给数据库的日期分开很容易。

<asp:Textbox id="date" runat="Server"></asp:Textbox>

<cc1:CalendarExtender ID="calwhendate" runat="server" Enabled="true" Format="YYYYMMDD"
TargetControlID="date"></cc1:CalendarExtender>

Change your Ajax Calendar Control to your desired format 将您的Ajax日历控件更改为所需的格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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