MsgBox和SQL'Insert Into'查询

时间:2018-01-09 22:16:31

标签: sql ms-access access-vba

在MS-Access数据库中,我从VBA模块触发了以下SQL查询,该模块根据WHERE子句中声明的条件附加记录。我的问题是,我可以插入一个MsgBox,告知用户记录是否已存在或天气是否为新记录?如果名为“Counterparty ID”的字段的值已经在目标表中,则查询将追加记录,如果不存在则不会。虽然机制是正确的,但我想通知用户他/她是否尝试插入重复记录。这有点可能吗?我认为它必须在查询本身内发生。

"INSERT INTO Netting_Determinations_List ([Counterparty ID], [Counterparty Name], [Counterparty Type], [Counterparty Subtype],[DTCC_AVOX_Registered_LEI_CICI], " & _
        "[Data Point 1],[Data Point 2],[Data Point 3],[Data Point 4],[Data Point 5], [Matrix Legal Form], [Matrix Governing/Authorizing Power], " & _
        "[OnBoardings Color Determination], [Matrix Clarification],  [Audit_Append_User], [Audit_Append_Date], [Audit_Append_Time]) " & _
        "SELECT Repository_Redux.[Counterparty ID], Repository_Redux.[Counterparty Name], Repository_Redux.[Counterparty Type], Repository_Redux.[Counterparty Subtype], Repository_Redux.[DTCC_AVOX_Registered_LEI_CICI], " & _
        "[Forms]![Frm_Master_Form]![Txt_Input_1] AS [Data Point 1], [Forms]![Frm_Master_Form]![Txt_Input_2] AS [Data Point 2], " & _
        "[Forms]![Frm_Master_Form]![Txt_Input_3] AS [Data Point 3], [Forms]![Frm_Master_Form]![Txt_Input_4] AS [Data Point 4], " & _
        "[Forms]![Frm_Master_Form]![Txt_Input_5] AS [Data Point 5], [Forms]![Frm_Master_Form]![Cbo_LegalForm] AS [Matrix Legal Form], " & _
        "[Forms]![Frm_Master_Form]![Cbo_Status] AS [Matrix Governing/Authorizing Power], [Forms]![Frm_Master_Form]![Txt_Color] AS [OnBoardings Color Determination], " & _
        "[Forms]![Frm_Master_Form]![Txt_Matrix_Clarification] AS [Matrix Clarification], '" & strUsername & "' AS [Audit_Append_User], " & _
        "'" & StrDate & "' AS [Audit_Append_Date], '" & StrTime & "' AS [Audit_Append_Time] FROM Repository_Redux " & _
        "WHERE Repository_Redux.[Counterparty ID] IN (" & strCriteria & ") AND NOT EXISTS (SELECT [Counterparty ID] FROM Netting_Determinations_List WHERE [Counterparty ID] = (" & strCriteria & "))"

2 个答案:

答案 0 :(得分:2)

我会这样做:

If Nz(DLookup("Counterparty ID","Netting_Determinations_List","[Counterparty ID]=" & strCriteria),0)=0 then
--Record does not exists, insert
else
--record exists notify user
end if

不要试图找出是否插入了记录。更容易检查记录并相应采取行动。

答案 1 :(得分:0)

MS Access在处理记录方面非常简单。例如,您可以从VBA调用插入(Database.Execute“insert ...”),它可能无法插入;你必须去验证你想要写的东西实际上是插入的。 (但是DoSQL操作会弹出对话框。)

由于您使用的是VBA,我建议您先自己在SQL中进行测试。创建查询对象或执行选择是否存在记录的查询文本(Recordset.RecordCount> 0),然后弹出一个对话框,通知用户它。您无法将其写入查询文本。

请注意,您可能需要执行.MoveLast和.MoveFirst来获取实际记录数,具体取决于记录集类型。