2017-08-20 75 views
0

我有一個表tblCosts,它顯示在msaccess前端,使用戶可以添加新條目以及更新現有條目。該表的結構如下。
更新條件vs插入

ExpenseType  Month  Year  Cost 
Hardware   June  2017  $500 
Software   July  2017  $300 
Hardware   Sept  2017  $150 

我有一個更新和插入手動運行時做工精細的查詢。 但是我在區分條件何時在表單上激發查詢時遇到了問題。例如,如果記錄存在於表中,它應該運行更新查詢,如果記錄不存在,它應該運行插入查詢。

例如,如果有人把在
- 硬件       九月    2017年    $ 120
應該更新150第三項120,但如果有人把在
- 傢俱       九月    $ 350
它應該認識到傢俱不是數據庫的一部分並運行插入查詢。
我有更新並插入查詢,但需要幫助來確定何時運行它們的條件。

我使用的更新查詢是:我使用

Update tblCosts 
set tblCosts.Cost=[Forms]![frmCost]![txtCost] 
where tblCosts.ExpenseType = [Forms]![frmCost]![txtExpType] 
and tblCosts.Month = [Forms]![frmCost]![txtMonth] 
and tblCosts.Year = [Forms]![frmCost]![txtYear] 

插入查詢是:

Insert into tblCosts (ExpenseType , Month, Year, Cost) 
Select [Forms]![frmCost]![txtExpType] as Exp1, 
[Forms]![frmCost]![txtMonth] as Exp2, 
[Forms]![frmCost]![txtYear] as Exp 3, 
[Forms]![frmCost]![txtCost] as Exp 4 
+0

嘗試使用'DCount'來檢查是否已有條目?請向我們展示您的嘗試,以及您如何觸發查詢(宏或VBA)。 –

+0

我的嘗試基於msaccess無界前端,更新查詢「更新tblCosts集tblCosts.Cost = [Forms]![frmCost]![txtCost]其中tblCosts.ExpenseType = [Forms]![frmCost]![txtExpType]和tblCosts.Month = [Forms]![frmCost]![txtMonth]和tblCosts.Year = [Forms]![frmCost]![txtYear] – Anup

+0

並插入查詢:Insert into tblCosts(ExpenseType,Month,Year,Cost)Select [Forms]![frmCost]![txtExpType] as Exp1,[Forms]![frmCost]![txtMonth] as Exp2,[Forms]![frmCost]![txtYear] as Exp 3,[Forms]![frmCost]![txtCost] as Exp 4就像我說的那樣,當我手動運行它們時,update和insert查詢都會運行,它只是我需要觸發條件的幫助(如果新記錄插入,如果現有記錄更新) – Anup

回答

1

需要代碼(VBA或宏),確定哪個動作的形式背後查詢運行。在VBA中有這樣的:

If DCount("*", "tablename", "ExpenseType='" & Me.cbxExpense & "' AND [Month]='" & Me.tbxMonth & "' AND [Year]=" & Me.tbxYear) = 0 Then 
    CurrentDb.Execute "INSERT INTO tablename (Expense, [Month], [Year], Cost) VALUES ('" & Me.cbxExpense & "', '" & Me.tbxMonth & "', " & Me.tbxYear & ", " & Me.tbxCost & ")" 
Else 
    CurrentDb.Execute "UPDATE tablename SET Cost=" & Me.tbxCost & " WHERE Expense='" & Me.cbxExpense & "' AND [Month]='" & Me.tbxMonth & ", [Year]=" & Me.tbxYear 
End If 

也許還需要一些驗證代碼來確保所有四個控件在執行查詢之前都有數據。

真正的訣竅在於確定將代碼置於哪個事件中 - 只要其他字段首先輸入了數據,Cost AfterUpdate將會工作,否則驗證將失敗,用戶將不得不重新輸入成本。

可能有讓每個控件都可用的代碼,直到輸入上一個值。

月和年是保留字,不應使用保留字作爲任何名稱。

爲了排序目的,最好保存月份數字而不是月份名稱。

爲什麼更新一個真正應該是計算的交易記錄集合的值?

+0

完全同意這裏的一切。 –

+0

爲我工作。謝謝June7 – Anup

+0

很高興它的工作,並做了我的答案編輯。 – June7