英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论