首页 > 解决方案 > 无效的 SQL 语句;在 SQL 语句中使用 IF EXISTS() 时出错,OLEDB MS ACCESS

问题描述

我正在尝试构建一个 SQL 语句,该语句将在数据库中插入或更新一行,具体取决于它是否已经存在于表中。当我连接到 MSSQL 服务器时,这种格式似乎有效,但当我使用 OLEDB 连接到 MS Access 时,这种格式无效。

IF EXISTS(select * from Resistors where ID = 2816)
    update Resistors set
    [Part Number]='1234'
    where ID = 2816
else
    insert into Resistors (
    [Part Number]
    )
    values(
    '1234'
    )
;

我已经使用 OLEDB 连接到 MS Access 验证了这两个 sql 命令。它们可以正常工作,但现在使用命令的 IF EXISTS() 部分。

update Resistors set
[Part Number]='1234'
where ID = 2816


insert into Resistors (
[Part Number]
)
values(
'1234'
)

IF EXISTS() 语句似乎与我在互联网上看到的其他文档相匹配,但我一定做错了。

这是我在运行命令时收到的错误。

Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.

这是我的连接字符串

connection.ConnectionString = "Provider = Microsoft Office 12.0 Access Database Engine OLE DB Provider; Data source = " + _database_path;

这个连接接口不支持exists命令吗?有支持exists命令的版本吗?

标签: sqlms-access

解决方案


不幸的是,MS-Access sql 不支持 ifexists()。

您可以使用select count()作为解决方法,如果返回 0 则它不存在。

...
string cmdstr = "SELECT COUNT(*) FROM Resistors where ID = 2816";
....
int count = (int)command.ExecuteScalar();
....
if (count=0)
....

我希望这可能会有所帮助


推荐阅读