SQL Server存储过程 - 将数据类型varchar转换为datetime时出错

时间:2016-03-08 18:27:33

标签: sql sql-server tsql datetime stored-procedures

我有这个存储过程:

xlChart.Series[0].Points[0].Color = Color.Red;
xlChart.Series[0].Points[1].Color = Color.Blue;

当我尝试执行它时:

ALTER PROCEDURE [dbo].[PostScheduledTasks] 
    @actualStart datetime = NULL, 
    @actualFinish datetime = NULL,
    @actualEndDate datetime = NULL,
    @UserDate1 datetime = NULL,
    @IsCompleted bit = 0,
    @PercentComplete float = 0.0,
    @UStmp varchar(10) = NULL,
    @SchedukeTaskID int = 0,
    @SortOrder int = 0
AS
BEGIN
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    UPDATE ScheduleTasks  
    SET ActualStart = @actualStart,
        ActualFinish = @actualFinish,
        ActualEndDate = @actualEndDate,
        UserDate1 = @UserDate1,
        IsCompleted = @IsCompleted,
        PercentComplete = @percentComplete,
        UStmp = @UStmp
    WHERE 
        ScheduleTaskID = @SchedukeTaskID
        AND SortOrder = @SortOrder
END

我收到此错误:

  

将数据类型varchar转换为datetime时出错。

1 个答案:

答案 0 :(得分:5)

最安全的方法是提供与文化无关的ISO 8601日期:

  

YYYY-MM-DDTHH:MM:SS [.mmm]

     

使用ISO 8601格式的优势在于它是一种国际标准。此外,使用此格式指定的日期时间值是明确的。此外,此格式不受SET DATEFORMAT或SET LANGUAGE设置的影响。

DECLARE @return_value int

EXEC    @return_value = [dbo].[PostScheduledTasks]
        @actualStart     = N'2016-03-08T08:00:00',
        @actualFinish    = N'2016-03-08T16:00:00',
        @actualEndDate   = N'2016-03-08T16:00:00',
        @UserDate1       = N'2016-01-27T08:00:00',
        @IsCompleted     = 1,
        @PercentComplete = 1,
        @UStmp           = N'jsuske',
        @SchedukeTaskID  = 597295,
        @SortOrder       = 19

SELECT  'Return Value' = @return_value

或者您必须检查SET LANGUAGE/DATEFORMAT并以正确的格式提供日期。