sql - Condition for Update vs insert -
i have table tblcosts display on msaccess front end enables users add new entries update existing ones. table structured below.
expensetype month year cost hardware june 2017 $500 software july 2017 $300 hardware sept 2017 $150
i have update , insert queries work fine when run manually. having trouble differentiating condition when fire query on form. example, if record exists in table, should run update query, if record not exist, should run insert query.
for example if puts in
- hardware sept 2017 $120
should update 3rd entry 150 120 if puts in
- furniture sept 2017 $350
should recognize furniture not part of db , run insert query.
have update , insert queries need in identifying condition when run them.
the update query i'm using is:
update tblcosts set tblcosts.cost=[forms]![frmcost]![txtcost] tblcosts.expensetype = [forms]![frmcost]![txtexptype] , tblcosts.month = [forms]![frmcost]![txtmonth] , tblcosts.year = [forms]![frmcost]![txtyear]
the insert query i'm using is:
insert tblcosts (expensetype , month, year, cost) select [forms]![frmcost]![txtexptype] exp1, [forms]![frmcost]![txtmonth] exp2, [forms]![frmcost]![txtyear] exp 3, [forms]![frmcost]![txtcost] exp 4
need code (vba or macro) behind form determines action query run. in vba like:
if dcount("*", "tablename", "expensetype='" & me.cbxexpense & "' , [month]='" & me.tbxmonth & "' , [year]=" & me.tbxyear) = 0 currentdb.execute "insert tablename (expense, [month], [year], cost) values ('" & me.cbxexpense & "', '" & me.tbxmonth & "', " & me.tbxyear & ", " & me.tbxcost & ")" else currentdb.execute "update tablename set cost=" & me.tbxcost & " expense='" & me.cbxexpense & "' , [month]='" & me.tbxmonth & ", [year]=" & me.tbxyear end if
probably want validation code make sure 4 controls have data before executing queries.
the real trick figuring out event put code - cost afterupdate work long other fields have data entered first, otherwise validation fail , user have re-enter cost.
could have code doesn't make each control available until previous value entered.
month , year reserved words , should not use reserved words names anything.
would better save month numbers instead of month names sorting purposes.
why updating value should calculated aggregation of transaction records?
Comments
Post a Comment