Access 2003中的SQL:INSERT INTO和多个SELECT查询

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Access 2003中的SQL:INSERT INTO和多个SELECT查询相关的知识,希望对你有一定的参考价值。

我正在使用Access 2003(由于反向兼容性而被迫这样做)来修改一个10年前的项目,而不是我做的。我在执行此查询时遇到错误:

INSERT INTO ClientiContratto ( ID, CLIENTE, DATA, PERIODO, IMPORTO, FATTURATO )
SELECT [Forms]![InserisciContratto]![Cliente] AS Espr1, (SELECT Nome from TAnagrafica WHERE TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]) AS Espr2, [Forms]![InserisciContratto]![Data] AS Espr3, [Forms]![InserisciContratto]![Periodo] AS Espr4, [Forms]![InserisciContratto]![Importo] AS Espr5, False AS Espr6;

这会返回由于的错误

 (SELECT Nome from TAnagrafica WHERE TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]) AS Espr2

如果我独立执行此查询,它就像一个魅力,但是当它将查询插入INSERT INTO ... SELECT语句时,它返回(从意大利语翻译):

运行时错误'3000':保留错误(-3025):此错误没有消息。

目的是在表格中插入一些基于活动形式中找到的值的新值,而不起作用的代码部分应该在表格中搜索与[​​InserisciContratto]![Cliente]实际值相关联的值。

我究竟做错了什么?也许是因为我无法在之前的SELECT查询中执行SELECT子查询?

任何帮助,将不胜感激。

答案

您可以使用DLookUp而不是子查询来解决此问题:

DLookUp("Nome", "TAnagrafica", "TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]")

请注意,您可以在表单控件或查询中使用DLookUp。两者都有效。在查询中,它看起来像这样:

INSERT INTO ClientiContratto ( ID, CLIENTE, DATA, PERIODO, IMPORTO, FATTURATO )
SELECT [Forms]![InserisciContratto]![Cliente] AS Espr1, DLookUp("Nome", "TAnagrafica", "TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]") AS Espr2, [Forms]![InserisciContratto]![Data] AS Espr3, [Forms]![InserisciContratto]![Periodo] AS Espr4, [Forms]![InserisciContratto]![Importo] AS Espr5, False AS Espr6;

这类错误的另一个常见来源是,在使用子查询而不是从真实表中查询时,Access的行为很糟糕。您可以使用子查询作为主查询轻松解决此问题。请注意,这确实需要子查询始终返回结果,否则不会插入任何行:

INSERT INTO ClientiContratto ( ID, CLIENTE, DATA, PERIODO, IMPORTO, FATTURATO )
SELECT [Forms]![InserisciContratto]![Cliente] AS Espr1, Nome AS Espr2, [Forms]![InserisciContratto]![Data] AS Espr3, [Forms]![InserisciContratto]![Periodo] AS Espr4, [Forms]![InserisciContratto]![Importo] AS Espr5, False AS Espr6
FROM TAnagrafica
WHERE TAnagrafica.IDAnagr = [Forms]![InserisciContratto]![Cliente]

以上是关于Access 2003中的SQL:INSERT INTO和多个SELECT查询的主要内容,如果未能解决你的问题,请参考以下文章

MS Access 2003 - Unbound Form 使用 INSERT 语句保存到表中;子表单呢?

Access 2003 SQL Switch 会破坏数据类型?

Access 2010 中的 INSERT INTO 语句中出现 SQL 语法错误

access SQL语句中 insert into

MS-Access:SQL JOIN 和 INSERT INTO 与 WHERE 慢

Access 2003 - 表单上另一个数据库中的字段