INSERT INTO:两个查询,几乎相同,只有一个有效

时间:2017-10-24 02:17:24

标签: sql ms-access

已更新 我正在构建一个密钥库存管理数据库,并构建了一个INSERT INTO查询来记录Key-OUT事务。我已经尝试构建一个Key-IN查询来做几乎相同的事情,但我得到了一个密钥违规。

以下SQL有效:

INSERT INTO KeyTransactions (Request, Door, Quantity) 
SELECT KeyRequests.RequestID, KeyRequests.Door, KeyRequests.Quantity
FROM KeyRequests
WHERE ((KeyRequests.RequestID)=4);

但这不是:

INSERT INTO KeyTransactions (Request, Door, Quantity) 
SELECT KeyReturns.ReturnID, KeyReturns.Door, KeyReturns.Quantity
FROM KeyReturns
WHERE ((KeyReturns.ReturnID)=2);

应该注意:作为一个简单的查询运行正常,只有第二个作为更新查询运行时才会出现密钥违规错误。

为了记录,在缩小罪魁祸首之前,以下是原始帖子:

我一直在构建MS Access应用程序来跟踪密钥库存,我正在尝试构建"库存IN"功能。我的"库存OUT"功能很好,但当我试图复制几乎完全相同的程序,但稍微扭曲,我什么也得不到。没有错误,没有插入记录,没有任何可辨别的行为,这使得调试或研究我的答案非常困难。

作为参考,这里是"库存IN"有效的sql:

sqlDoorToMark = "SELECT Spaces_Table.Door, Keys_Table.Mark FROM Keys_Table INNER JOIN Spaces_Table ON Keys_Table.[ID] = Spaces_Table.[AssignedKey] WHERE Spaces_Table.[Door] = " & Me.Door & ";"
Set rs = myDB.OpenRecordset(sqlDoorToMark)
sqlIssuedInventoryUpdate = "INSERT INTO IssuedInventory (RequestID, Door, KeyMark, Quantity, IssueDate) VALUES (" & Me.RequestID & ", " & Me.Door & ", '" & rs!mark & "', " & Me.Quantity & ", Date());"
myDB.Execute sqlIssuedInventoryUpdate

显然有更多的代码可以解决这个问题。在更新下拉框后调用此方法。工作完美。喜欢它。

以下是"库存IN"的全部内容。单击“提交”按钮调用的代码:

Private Sub Submit_btn_Click()
Dim myDB As Database
Dim rs As DAO.Recordset

On Error Resume Next
On Error GoTo PROC_ERR

Set myDB = CurrentDb

sqlGetReturnValues = "SELECT KeyReturns.ReturnID, Keys_Table.Mark, KeyReturns.Quantity FROM KeyReturns INNER JOIN Keys_Table ON KeyReturns.Mark = Keys_Table.ID;"
Set rs = myDB.OpenRecordset(sqlGetReturnValues)

sqlInsertReturn = "INSERT INTO IssuedInventory (RequestID, Door, KeyMark, Quantity, IssueDate) VALUES (" & rs!ReturnID & ", '0000', '" & rs!mark & "', " & rs!Quantity & ", Date());"
myDB.Execute sqlInsertReturn

Set rs = Nothing
Set myDB = Nothing

PROC_EXIT:
    Exit Sub

PROC_ERR:
    MsgBox Err.Description
    Resume PROC_EXIT
End Sub

运行调试器,我可以浏览每一行并监视通过的值。一切都很好。据我所知,.Execute sqlInsertReturn命令只是在这里没有做任何事情。

你能看到我没见过的东西吗?

1 个答案:

答案 0 :(得分:1)

第一个方法的第二个参数,即有效的方法,不使用单引号。这使我相信Door必须是数值而不是字符串值。

INSERT INTO IssuedInventory (RequestID, Door, KeyMark, Quantity, IssueDate) VALUES (    ,       ,''  ,    ,  Date());

INSERT INTO IssuedInventory (RequestID, Door, KeyMark, Quantity, IssueDate) VALUES (    ,'0000', ''  ,    , Date());

我建议专门为插入新记录创建一个子程序。

Sub InsertDoor(lRequestID As Long, lDoor As Long, sKeyMark As String, sQuantity As Single, dIssueDate As Date)
    On Error GoTo PROC_ERR
    CurrentDb.Execute "INSERT INTO IssuedInventory (RequestID, Door, KeyMark, Quantity, IssueDate) " & _
                      "VALUES (" & lRequestID & ", lDoor, '" & sKeyMark & "', " & sQuantity & ", dIssueDate);"
PROC_EXIT:
    Exit Sub

PROC_ERR:
    MsgBox Err.Description
    Resume PROC_EXIT
End Sub