2013-09-24 313 views
5

如果插入的變量的值爲Null,則SQL INSERT INTO將失敗。如果插入值爲Null的變量,INSERT INTO會失敗

變量costLab是Variant數據類型。非空值將是十進制。

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的方式。

回答

6

當您構建INSERT語句時,您可以使用Nz()。它類似於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視圖中進行測試。

+0

感謝Hans的快速反應。我仍然想知道爲什麼它首先失敗。例如,使用基於字段值爲null的表的SELECT的插入沒有任何問題。 – dblE

+0

檢查'Debug.Print'的輸出。我的猜測是,當'costLab'爲空時,從原始代碼構建的語句的最後部分將是...''Forecast',);' – HansUp

+0

隨着我建議的代碼,聲明的最後部分將結束當'costLab'爲空時...''Forecast',Null);' – HansUp

1

只要在costLab爲空時直接插入「空」即可。

所以,當您連接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),但這是我能想到的最短的形式。

+0

感謝您的快速反應基督教。這是一個有效的解決方法,我明白,我不明白爲什麼我不能簡單地使用變量插入值null。它爲什麼會失敗? – dblE