将varchar数据类型转换为日期时间数据类型会导致超出范围的值 - 存储过程

时间:2014-10-01 10:53:58

标签: c# sql sql-server datetime

我有存储过程,它检查日期是否在一个工作日,如果是nessecary则更改它。我在视觉工作室中调用此proc,如下所示。但是,当proc运行时,我收到The conversion of a varchar data type to a datetime data type resulted in an out-of-range value消息。当我在SQL Server Management Studio中使用与Visual Studio中使用的相同值运行相同的proc时,它可以工作。

ALTER PROCEDURE [dbo].[usp_PSTN_GetWorkingDay]

    @TargetDate VARCHAR(30)

AS  

BEGIN

    SET NOCOUNT ON;

    /* Workout 10 working days from present date */
    DECLARE @MaxDateCantBook DATETIME

    ;WITH DatesCTE AS
    (
        SELECT Date_Id,
               Date_Date,
               Date_JDE,
               Is_WorkingDay,
               ROW_NUMBER() OVER(ORDER BY Date_Date) AS rn
        FROM   dbo.Dates
        WHERE  Is_WorkingDay = 1
               AND Date_Date > GETDATE()
    )

    SELECT @MaxDateCantBook = (SELECT Date_Date FROM DatesCTE WHERE rn = 10)                                      

    /* Change Target date if it is less than 10 working days in the future */
    IF(@TargetDate <= @MaxDateCantBook)
    BEGIN

        SET @TargetDate = @MaxDateCantBook
    END


    SELECT Date_Date
    FROM dbo.Dates
    WHERE Date_Date >= @TargetDate
    AND Date_Date <= (SELECT MIN(Date_Date) 
                        FROM dbo.Dates 
                        WHERE Is_WorkingDay != 0 AND Date_Date >= @TargetDate)
    ORDER BY Date_Date DESC


END 

我正在设置查询的参数,如下所示:

List<SqlParameter> parameters = new List<SqlParameter>()
              {
                  new SqlParameter("TargetDate", SqlDbType.VarChar, 30){ Value = input.date}
              };

其中input.date是字符串= 2014-09-30

1 个答案:

答案 0 :(得分:1)

在您的SP中将@TargetDate VARCHAR(30)更改为@TargetDate DATETIME

设置参数时可以按照以下步骤进行操作

cmd.Parameters.AddWithValue("@TargetDate",
         DateTime.ParseExact(input.date, "yyyy-MM-dd", CultureInfo.InvariantCulture));

List<SqlParameter> parameters = new List<SqlParameter>()
              {
                  new SqlParameter("@TargetDate", SqlDbType.DateTime){ Value = DateTime.ParseExact(input.date, "yyyy-MM-dd", CultureInfo.InvariantCulture)}
              };