如何解决“错误转换数据类型varchar到日期”
问题描述:
我有这样的存储过程。如果我试图在6月1日至7月31日执行它,则会显示转换错误。任何人都可以请帮助如何解决这个问题?它显示了7月6日和7月1日的结果正常工作。但如果我7月31日使用它不起作用。如何解决“错误转换数据类型varchar到日期”
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
答
SQL服务器使用这些隐式转换美国的日期格式(MM/DD/YYYY),所以在进入'01/06/2015'
实际上是转换为6日2015年1月的,这显然是一个有效的日期。如果您输入'31/07/2015'
SQL服务器将尝试将其转换为第31个月的第7天,这是无效的,以及为什么会出现转换错误。
另外,在您的示例中,您已指定2015年6月31日,该日期不是日期。
你应该尝试把你的代码分解到导致问题的部分 –
a.Auditor_Reviewed_Date列是nvarchar(max)数据类型.. – Perumal
[踢坏坏习惯:选择错误的数据类型](http:// sqlblog .com/blogs/aaron_bertrand/archive/2009/10/12/bad-habits-to-kick-using-the-wrong-data-type.aspx) - 你应该总是使用最合适的数据类型 - 毕竟是在那里!如果你有一个**日期** - 你应该**这样存储它!**不要将日期保存为'varchar',绝对不是'varchar(max)'(或者你有没有看过日期** ** –