使用大小写SQL和VBA更新功能

时间:2012-12-28 19:33:30

标签: sql vba

我想尝试使用SQL函数来更新我的表并在列中添加日期,我正在使用带有大小写的更新函数,但是我得到了运算符丢失的错误。

但我找不到错误,有人知道它在哪里吗?

Public Function Add_date( _
                        ByVal startDate As String, _
                        ByVal strTableName As String, _
                        ByVal strFieldName As String, _
                        ByVal strNummeringField As String) _
                        As Boolean

Dim strSql As String
    strSql = "ALTER TABLE " & strTableName & " ADD " & strFieldName & " date"
    DoCmd.RunSQL strSql
    strSql = "UPDATE " & strTableName & " SET " & strFieldName & " = CASE WHEN " & strNummeringField & " < 25 THEN '23-07-1991' ELSE '01-01-01' END"
    MsgBox strSql
    DoCmd.RunSQL strSql


End Function

2 个答案:

答案 0 :(得分:1)

Jet / ACE(MS Access数据库引擎)不支持CASE ... WHEN。三元运算的等价物是IIF(即时)。此外,日期分隔符为#,而非'。试试这个:

strSql = " UPDATE " & strTableName & _
         " SET " & strFieldName & " = " & _
         "     IIf(" & strNummeringField & " < 25, #23-07-1991#, #01-01-01#)"

此外,无论您的区域设置如何,您都可能会在将日期格式化为DD-MM-YYYY时遇到问题。有关详细信息,请参阅International Dates in Access

答案 1 :(得分:0)

一种可能性是表示表和列名称的字符串包含无效字符。尝试将它们放在方括号中:

strSql = "ALTER TABLE [" & strTableName & "] ADD [" & strFieldName & "] date"
DoCmd.RunSQL strSql
strSql = "UPDATE [" & strTableName & "] SET [" & strFieldName & "] = CASE WHEN [" & strNummeringField & "] < 25 THEN '23-07-1991' ELSE '01-01-01' END"