我正在制作一个相当简单的库存跟踪数据库。我想按ID检索记录,并在金额中添加或删除指定的数字。如果它不存在我想添加它。是否可以在不绑定表的情况下执行此操作?
答案 0 :(得分:1)
我不知道你想要什么,但是这段代码展示了如何使用VB-Access操作数据。
Sub fnStudent()
On Error GoTo insertError
Dim studentQuery As String
'INSERTING INTO TABLE
studentQuery = "INSERT INTO Students values ('10','YAHYA','02/10/2012')"
CurrentDb.Execute studentQuery, dbFailOnError
'UPDATING
studentQuery = "UPDATE Students Set name='YAHYA OULD ABBA' WHERE stdID='10'"
CurrentDb.Execute studentQuery, dbFailOnError
'LISTING VALUES
Dim studentsRS As Recordset
Set studentsRS = CurrentDb.OpenRecordset("SELECT * FROM Students WHERE upper(name) like '%YAHYA%';")
Do While Not studentsRS.EOF
MsgBox "ID : " & studentsRS.Fields(0) & "Name : " & studentsRS.Fields(1) & "Birth Date : " & studentsRS.Fields(2)
studentsRS.MoveNext
Loop
'DELETING
studentQuery = "DELETE FROM Students WHERE stdID='10'"
CurrentDb.Execute studentQuery, dbFailOnError
Exit Sub 'exit if there was no error
'UPDATE:
errorHandler:
If Err.Number = 3022 Then
MsgBox "Can't have duplicate key; index changes were unsuccessful", vbMsgBoxRtlReading + vbCritical, "Error " & Err.Number
Else : MsgBox "Error" & vbCrLf & Err.Description, vbMsgBoxRtlReading + vbCritical, "Error " & Err.Number
End If
End Sub
在这里,您可以找到vba
错误http://www.halfile.com/vb.html
答案 1 :(得分:1)
听起来你有一个候选ID
值。也许它包含在一个名为MyID
的数字变量中。您还有另一个数值MyAmtChange
,要将amount
字段值匹配的行ID
添加到表中名为MyID
的字段中的值}。
复杂的是,您的表中可能没有ID
值与MyID
匹配的行。在这种情况下,您需要为其添加一行。
如果这是正确的,INSERT
当MyID
不存在时,UPDATE
行。然后,您只需amount
匹配MyID
的行中的Dim strInsert As String
Dim strUpdate As String
Dim db As DAO.Database
Set db = CurrentDb
If DCount("*", "YourTableNameHere", "ID = " & MyID) = 0 Then
strInsert = "INSERT INTO YourTableNameHere (ID)" & vbCrLf & _
"VALUES (" & MyID & ");"
Debug.Print strInsert
db.Execute strInsert, dbFailOnError
End If
strUpdate = "UPDATE YourTableNameHere" & vbCrLf & _
"SET amount = Nz(amount, 0) + " & MyAmtChange & vbCrLf & _
"WHERE ID = " & MyID & ";"
Debug.Print strUpdate
db.Execute strUpdate, dbFailOnError
Set db = Nothing
。
dbFailOnError
如果这个猜测相当接近,请在该代码中添加一个错误处理程序块,以处理由{{1}} ...或任何其他错误浮出的任何问题。