5

如果我插入的变量的值为 Null,则 SQL INSERT INTO 将失败。

变量 costLab 是 Variant 数据类型。非 Null 值将是 Decimal。

db.Execute ("INSERT INTO budget 
(wbsid, category, capture_date, budget_date, budget_type, month_value) " & _
"VALUES ('" & wbsid & "', 'Labor', #" & importDate & "#, 
#" & monthDate & "#, 'Forecast', " & costLab & ");")

如果设置 costLab 的代码返回 Null,我想插入 Null。但是如果返回一个值,我想插入那个值。显然,我可以编写一个 If 语句来检查 null,然后直接插入“Null”,但我想知道是否有没有 If 语句通过变量插入 Null 的方法。

4

2 回答 2

6

您可以Nz()在构建INSERT语句时使用。它与IIf()方法类似,但更简洁一些。

Dim strInsert As String
strInsert = "INSERT INTO budget (wbsid, category, capture_date, budget_date, budget_type, month_value) " & _
        "VALUES ('" & wbsid & "', 'Labor', #" & importDate & "#, #" & monthDate & "#, 'Forecast', " & Nz(costLab, 'Null') & ");"
Debug.Print strInsert ' <- examine the finshed statement in Immediate window
db.Execute strInsert, dbFailOnError

Debug.Print让您有机会检查您提供给数据库引擎执行的已完成语句。如果遇到问题,您可以转到立即窗口(Ctrl+g)查看语句文本。您还可以复制该文本并将其粘贴到新查询的 SQL 视图中以进行测试。

于 2013-09-24T18:52:57.500 回答
1

costLab当为 Null时,只需从字面上插入“null” 。

因此,当您连接 SQL 字符串而不是变量costLab时,您只需插入以下内容:

IIf(IsNull(costLab), "null", costlab)

完整的查询:

db.Execute ("INSERT INTO budget (wbsid, category, capture_date, budget_date, budget_type, month_value) " & _
    "VALUES ('" & wbsid & "', 'Labor', #" & importDate & "#, #" & monthDate & "#, 'Forecast', " & IIf(IsNull(costLab), "null", costlab) & ");")

我知道...从技术上讲,这一个If陈述(IIf只是 的一种简短形式If...Then...Else),但它是我能想到的最短形式。

于 2013-09-24T18:48:30.697 回答