Oracle SQL变量:带有STRING IN子句中值列表的SELECT

时间:2018-06-01 18:13:17

标签: sql oracle variables select

这是正常的:

DEFINE numbers = '1,2,3,4,5';
SELECT * FROM table1 WHERE items IN (&numbers);

就像这样:

SELECT * FROM table1 WHERE items IN ('a','b','c','d'); error

这会返回 snytax错误

DEFINE letters = 'a','b','c','d';
SELECT * FROM table1 WHERE items IN (&letters);  -- result syntax ERROR

如何使用WHERE ... IN创建的字符串列表来使用DEFINE子句?

1 个答案:

答案 0 :(得分:4)

DEFINE值括在双引号中:

define letters = "'a','b','c','d'"

set verify on

select * from dual where dummy in (&letters);

old   1: select * from dual where dummy in (&letters)
new   1: select * from dual where dummy in ('a','b','c','d')

no rows selected

请注意,挑战实际上是如何DEFINE多字符串,因为它是同一个问题:

SQL> define letters = I love kittens
SQL> define letters
DEFINE LETTERS         = "I" (CHAR)

SQL> define letters = 'a','b','c','d'
SQL> define letters
DEFINE LETTERS         = "a" (CHAR)

双引号修复:

SQL> define letters = "I love kittens"
SQL> define letters
DEFINE LETTERS         = "I love kittens" (CHAR)

为了完整起见,设置define变量的另一种方法是使用select方法的column new_value语句。从历史上看,这是为在SQL * Plus报表中动态设置页面标题而提供的,但它在脚本中很方便。 (它也是将类型设置为number的唯一方法,而不是它有任何区别。)

SQL> col letters new_value letters
SQL> select q'{'a','b','c','d'}' as letters from dual;

LETTERS
---------------
'a','b','c','d'

1 row selected.

SQL> def letters
DEFINE LETTERS         = "'a','b','c','d'" (CHAR)

SQL> select 123.456 as letters from dual;

   LETTERS
----------
   123.456

1 row selected.

SQL> def letters
DEFINE LETTERS         =    123.456 (NUMBER)