如何解决"将数据类型varchar转换为日期错误"

时间:2015-09-07 09:18:54

标签: sql-server-2014

我有这样的存储过程。如果我尝试在7月1日到7月31日执行它,它会显示转换错误。任何人都可以帮助解决这个问题吗?它显示了7月1日和7月30日工作正常的结果。但是,如果我在7月31日使用它,它就不起作用了。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER procedure [dbo].[Samp]
      (@StartDate date ,
       @EndDate date,
       @Flowid int)
AS
BEGIN
    if(@Flowid = 909)
    begin
        select 
            COUNT(distinct a.Audit_id)  
        from  
            [Prod_Workflow_Client41].[dbo].[CustomValues909] a 
        join 
            [Prod_Workflow_Client41].[dbo].[Audit] b on a.id = b.id
        join 
            [Prod_Workflow_Client41].[dbo].[Substatus] c on c.Id = b.Substatus_id
        where 
            c.MajorStatus <> 'Cancelled' 
            and a.Auditor_Reviewed_Date >= @StartDate
            and a.Auditor_Reviewed_Date <= @EndDate
     end
     else if @Flowid = 1010
     begin 
         select 
             COUNT(distinct a.Audit_id)  
         from  
             [Prod_Workflow_Client41].[dbo].[CustomValues1010] a 
         join 
             [Prod_Workflow_Client41].[dbo].[Audit] b on a.id = b.id
         join 
             [Prod_Workflow_Client41].[dbo].[Substatus] c on c.Id = b.Substatus_id
         where 
             c.MajorStatus <> 'Cancelled' 
             and a.Auditor_Reviewed_Date >= @StartDate
             and a.Auditor_Reviewed_Date <= @EndDate
    end
    else if @Flowid = 101
    begin
        select 
            COUNT(distinct a.Audit_id)  
        from  
            [Prod_Workflow_Client41].[dbo].[CustomValues101] a 
        join 
            [Prod_Workflow_Client41].[dbo].[Audit] b on a.id = b.id
        join 
            [Prod_Workflow_Client41].[dbo].[Substatus] c on c.Id = b.Substatus_id
        where 
            c.MajorStatus <> 'Cancelled' 
            and a.Auditor_Reviewed_Date >= @StartDate
            and a.Auditor_Reviewed_Date <= @EndDate
   end
end
--exec [dbo].[Samp] '01/06/2015','31/06/2015',909
--exec [dbo].[Samp] '01/06/2015','30/06/2015',1010
--exec [dbo].[Samp] '01/06/2015','30/06/2015',101

1 个答案:

答案 0 :(得分:1)

SQL Server使用US日期格式(mm / dd / yyyy)进行这些隐式转换,因此输入'01/06/2015'实际上转换为 2015年1月6日,这显然是一个有效日期。如果您输入'31/07/2015' SQL服务器将尝试将其转换为第31个月的第7天,这将无效以及您收到转换错误的原因。

此外,在您的示例中,您已指定2015年6月31日,这不是日期。