sql - 无效的 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命令的版本吗?
解决方案
不幸的是,MS-Access sql 不支持 ifexists()。
您可以使用select count()作为解决方法,如果返回 0 则它不存在。
...
string cmdstr = "SELECT COUNT(*) FROM Resistors where ID = 2816";
....
int count = (int)command.ExecuteScalar();
....
if (count=0)
....
我希望这可能会有所帮助
推荐阅读
- typescript - Ionic 4:Ionic Lab 黑屏错误的解决方法
- python - Kivy 未正确显示(孟加拉语)Unicode 字符
- javascript - 无法解析 json 数据 jquery
- ios - 是否可以在 iOS 中实现对操作系统权限提示的分析?
- c# - .Net Web API 以毫秒为单位绑定日期时间
- google-cloud-platform - 使用不同的传出 IP 执行多个 Google Cloud Functions 的正确方法是什么?
- flutter - 从 IBM Watson 下载 CoreML 文件时出错
- excel - 使用列表中的名称创建新工作表
- rabbitmq - 使用 request-reply 和 pub-sub 进行微服务通信
- python - 针对工作日字符串使用 Pandas .corr