CAST - 数据类型 datetime 和 datetime2 在 add 运算符中不兼容

CAST - The data types datetime and datetime2 are incompatible in the add operator

我收到以下错误

Microsoft OLE DB Provider for SQL Server error '80040e14' The data types datetime and datetime2 are incompatible in the add operator.

 <%
Set cnnSimple = Server.CreateObject("ADODB.Connection")
cnnSimple.Open "Provider=SQLOLEDB.1;Initial Catalog=P;DataSource=S\SQLEXPRESS; Persist Security Info=True;User ID=xx;Password=xxxxxxx"

sql = "SELECT DISTINCT" & _
 "'<option value=""' + CAST([date_required] AS DATETIME) + '"">' + " & _
 "[date_required] + '</option>' " & _
  "FROM " & _
 "qryOutstandingPOLinesSource2 where supplier='" & suppliercode &"' and date_required < GETDATE()"

set rs = Server.CreateObject("ADODB.RecordSet")
rs.Open sql, cnnSimple, 0, 1, 1

if rs.eof then
no_rows3 = true
else
str = rs.GetString()
End If
%>

有解决办法吗?我试过转换为 VARCHAR 但没有用。

您只需将数据转换为 NVARCHAR,就像这样...

sql = "SELECT DISTINCT" & _
  "'<option value=""' + CONVERT(NVARCHAR, [date_required]) + '"">' + " & _
  "CONVERT(NVARCHAR, [date_required]) + '</option>' " & _
  "FROM " & _
  "qryOutstandingPOLinesSource2 where supplier='" & suppliercode &"' and date_required < GETDATE()"

根据 Lankmart 的评论进行编辑。使用 CONVERT 而不是 CAST 将允许略微更好的格式化能力,但它是 SQL 服务器特定的,而您可能会发现 CAST 在更广泛的范围内可用 T-SQL 实现。