如果不存在,则查询MS Access以插入记录

时间:2016-04-06 10:31:50

标签: mysql sql ms-access

这是一个MySql查询,这很好,但它不适用于MS-Access:

INSERT INTO ProcedureCodeModifier (ProcedureCode, Description)
SELECT * FROM
(
    SELECT 'A1', 'Dressing for one wound'
) AS tmp
WHERE NOT EXISTS (SELECT ProcedureCode FROM ProcedureCodeModifier
                  WHERE ProcedureCode = 'A1')
LIMIT 1;

3 个答案:

答案 0 :(得分:0)

删除LIMIT 1

在Access中这将是SELECT TOP 1 ...,但这里不需要它。

答案 1 :(得分:0)

如上所述here

我会这样做:检查代码是否存在于ProcedureCodeModifier表中,如果不存在,则运行Insert Into SQL。您可能需要稍微玩一下,这取决于您的代码字段是TEXT还是INT,但这应该可以帮助您完成任务。

Dim db as Database
Dim rec as Recordset
Dim sSQL as String

Set db = CurrentDB
Set rec = db.OpenRecordset("SELECT ProcedureCode FROM ProcedureCodeModifier WHERE ProcedureCode = 'A1'")

这会刷新数据集,以便您获得准确的记录计数     rec.MoveFirst     rec.MoveLast

如果你的记录数是0,那么代码还不在数据库中,所以你需要添加它

If rec.RecordCount = 0 Then
  sSQL = "INSERT INTO ProcedureCodeModifier (ProcedureCode, Description) VALUES ('A1', 'Dressing for one wound')";
  DoCmd.RunSQL sSQL
EndIf

始终将连接变量设置为Nothing,以便关闭连接!

Set db = Nothing
Set rec = Nothing

答案 2 :(得分:0)

“TOP 1”子句必须进入主查询。

INSERT INTO ProcedureCodeModifier (ProcedureCode, Description)
    SELECT TOP 1 
        'A1' AS ProcedureCode, 
        'Dressing for one wound' AS Description 
    FROM  
        ProcedureCodeModifier 
    WHERE 
        NOT EXISTS (SELECT TOP 1 ProcedureCode, Description 
                    FROM ProcedureCodeModifier 
                    WHERE ProcedureCode = 'A1');

如果ProcedureCodeModifier表为空或者表中只有一条记录,则子查询中必须省略“TOP 1”子句。我在子查询中使用了Top 1 Clause来解决一些性能问题。