代码之家  ›  专栏  ›  技术社区  ›  Anup

更新与插入的条件

  •  0
  • Anup  · 技术社区  · 8 年前

    我在msaccess前端显示了一个表tblCosts,它允许用户添加新条目以及更新现有条目。该表的结构如下。

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

    但是,我很难区分何时在表单上启动查询的条件。例如,如果记录存在于表中,则应运行更新查询,如果记录不存在,则应运行插入查询。



    它应该将第三个条目从150更新为120,但是如果有人输入
    -家具2017年9月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
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   June7    8 年前

    表单后面需要代码(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
    

    可能还需要一些验证代码,以确保在执行查询之前所有四个控件都有数据。

    可能有代码在输入前一个值之前无法使每个控件可用。

    为了便于排序,最好保存月份编号而不是月份名称。

    为什么要更新一个真正应该是交易记录计算汇总的值?