使用 Oracle SQL 中的 ‘define’ 关键字定义列表

huangapple go评论113阅读模式
英文:

using 'define' keyword for a list in oracle sql

问题

如何在Oracle SQL中使用define关键字来定义一个变量来保存一组数值,然后在select语句中使用该变量?

我在SQL文件中有以下内容:

define uniqueIds= [124,546,785,144];

select * from DATA_IDS where ID IN ('&uniqueIds');

但是当我运行它时,它给我报错:

ORA-01722: 无效的数字

我在Oracle SQL Developer IDE中运行这些命令。

英文:

How do I use the define keyword in oracle SQL for a variable to hold a list of numerical values. Then use that variable to be used in a select statement?

I have this in a SQL file:

define uniqueIds= [124,546,785,144];

select * from DATA_IDS where ID IN ('&uniqueIds');

But when I run it it gives me this error:

ORA-01722: invalid number

I'm running these commands in Oracle SQL Developer IDE.

答案1

得分: 3

DEFINE 是一个 SQL*Plus 命令,用于在 SQL*Plus(或 SQL Developer)客户端应用程序中声明替代变量。客户端应用程序会在本地评估替代变量,并通过执行从变量到其值的查找替换,有效地转换包含替代变量的 SQL 语句。

你想要的是:

DEFINE uniqueIds = 124,546,785,144

SELECT * FROM data_ids WHERE id IN (&uniqueIds);

或者,你可以简化脚本,跳过使用替代变量,直接使用:

SELECT * FROM data_ids WHERE id IN (124,546,785,144);

你的代码会生成以下语句:

select * from DATA_IDS where ID IN ('[124,546,785,144];');

假设 id 是一个 NUMBER 类型,那么你实际上正在尝试将 id 列与一个字符串文本进行比较(而不是与一组数字进行比较),这就是为什么你会收到 ORA-01722: invalid number 错误的原因(因为字符串文本无法隐式转换为数字)。

英文:

> How do I use the define keyword in oracle SQL

DEFINE is not an SQL keyword; it is an SQL*Plus command that declares a substitution variable in the SQL*Plus (or SQL Developer) client application.

The client application will evaluate the substitution variable locally and will effectively transform the SQL statement containing a substitution variable by performing a find-replace from the variable to its value.

You want:

DEFINE uniqueIds = 124,546,785,144

SELECT * FROM data_ids WHERE id IN (&uniqueIds);

Or, you can simplify the script and skip using a substitution variable and just use:

SELECT * FROM data_ids WHERE id IN (124,546,785,144);

Your code would generate a statement:

select * from DATA_IDS where ID IN ('[124,546,785,144];');

Assuming that id is a NUMBER then you are effectively trying to compare the id column to a string literal (and not to a list of numbers) which is why you get the error ORA-01722: invalid number (as the string literal cannot be implicitly cast to a number).

huangapple
  • 本文由 发表于 2023年6月9日 04:23:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435461.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定