COUNT(*)=0 计算结果为 true?
正如标题所说。我在 if 语句中有一条 SQL 语句 (Oracle 9),其计算结果为 true。据我所知,这样的语句将执行 SQL Server 中所期望的操作。在这种情况下我做错了什么?
IF (SELECT COUNT(*) FROM CUSTOMER_LIST WHERE CUSTOMER='Target')=0 THEN
INSERT INTO CUSTOMER_LIST (CUSTOMER_ID, CUSTOMER) VALUES
(CUSTOMER_ID_SEQ.nextval, 'Target')
或者更好的是,确保我不插入已经存在的数据的适当策略是什么。所编写的代码始终会插入。这显然不是我想要的,因为这一行已经存在。
当此代码运行时,我收到以下控制台消息。
Error starting at line 1 in command:
IF (SELECT COUNT(*) FROM CUSTOMER_LIST WHERE CUSTOMER='Target')=0 THEN
Error report:
Unknown Command
1 rows inserted.
Just like the title says. I have a SQL statement (Oracle 9) in an if statement that evaluates to true. From what I recall such a statement would do what is expected in SQL Server. What am I doing wrong in this case?
IF (SELECT COUNT(*) FROM CUSTOMER_LIST WHERE CUSTOMER='Target')=0 THEN
INSERT INTO CUSTOMER_LIST (CUSTOMER_ID, CUSTOMER) VALUES
(CUSTOMER_ID_SEQ.nextval, 'Target')
or better yet, what is an appropriate strategy to ensure that I do not insert data that already exists. The code as written always inserts. This obviously is not what I want since this row exists already.
When this code runs I get the following console message.
Error starting at line 1 in command:
IF (SELECT COUNT(*) FROM CUSTOMER_LIST WHERE CUSTOMER='Target')=0 THEN
Error report:
Unknown Command
1 rows inserted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题似乎是你在它期望直接 SQL 的地方给它 PL/SQL。要么直接给出 SQL:,
要么更改周围的上下文,以便 Oracle 期望 PL/SQL。这将取决于您如何传递此代码;但一种可能的方法是将其包装在
BEGIN ... END
块中。此外,您不能将查询用作 PL/SQL 中的表达式;如果您采用 PL/SQL 路线,则需要将结果存储在某个地方,例如变量中。总而言之,你可能会遇到这样的情况:
The problem seems to be that you're giving it PL/SQL where it's expecting straight SQL. Either give it straight SQL:
or else change the surrounding context so that Oracle will expect PL/SQL. That will depend on how you're passing this code in; but one likely way is to wrap it in a
BEGIN ... END
block.Additionally, you can't use a query as an expression in PL/SQL; if you go the PL/SQL route, you'll need to store the result somewhere, such as in a variable. All told, you might have this:
尝试类似的操作来检查是否从选择中返回了任何行。当选择没有返回元组时,NOT EXISTS 返回 true:
Try something like this to check if any rows are returned from the selection. NOT EXISTS returns true when no tuples were returned from the select: