将varchar值'08 / 22/1954'转换为数据类型int时转换失败

时间:2013-07-07 16:17:45

标签: vb.net date stored-procedures sqlcommand

我正在 stored procedure 中写 sql command ,如下所示:

Dim tdate As String = Me.PresentDate.Value.ToString("MM-dd-yyyy")

myCommand As New SqlCommand("select c.description as 'provider',b.lastname,
b.firstname, b.middleinitial,convert(varchar(10),b.dob,101) as DOB,
b.chartID,b.sex, d.businessname,d.businessfax from patientappointmentbase as a, 
patientlistbase as b,resourcebase as c, locationbase as d where convert(varchar(10),
a.starttime,101) = " & tdate & " 
and a.patientid = b.patientid and a.resourceid = c.resourceid and 
a.locationid = d.locationid order by provider, lastname, firstname", myConnection)

当我运行此代码时,我收到错误

Conversion failed when converting the varchar value '08/22/1954' to data type int.

2 个答案:

答案 0 :(得分:2)

您有两个主要问题。

第一个问题是日期被内联到SQL,以便您正在执行的SQL如下所示:

select ... where convert(varchar(10), a.starttime,101) = 07-07-2013

这不是有效的SQL,因此您需要将date参数包装在单引号中,即

... where convert(varchar(10), a.starttime,101) = '" & tdate & "' and ...

如果用双引号将其包装并且将QUOTED_IDENTIFIER设置为on,则SQL Server将尝试将其解释为列名。

第二个问题是您使用两种不同的日期格式进行比较。使用101样式转换会产生格式为mm / dd / yyyy的日期。但是,您使用的是mm-dd-yyyy格式。

这意味着您要求SQL服务器将“07/07/2013”​​与“07-07-2013”​​进行比较,这将永远不会相同。最简单的解决方法是更改​​tdate的日期格式以匹配SQL Server:

Dim tdate As String = Me.PresentDate.Value.ToString("MM/dd/yyyy")

答案 1 :(得分:0)

您的连接SQL字符串类似于

convert(varchar(10), a.starttime,101) = 08/22/1954

这是一系列除法操作,导致数字,而非日期。

您希望通过将值包装在引号中来创建日期文字 (或者,更好的是,使用参数)