在 IN 子句中为 NUMBER 列使用逗号分隔值

2023-11-02数据库问题
0

本文介绍了在 IN 子句中为 NUMBER 列使用逗号分隔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在一个包中有 2 个程序.我正在调用一个程序来获取用户 ID 的逗号分隔列表.

I have 2 procedures inside a package. I am calling one procedure to get a comma separated list of user ids.

我将结果存储在 VARCHAR 变量中.现在,当我使用此逗号分隔列表放入 IN 子句中时,它会抛出ORA-01722:INVALID NUMBER" 异常.

I am storing the result in a VARCHAR variable. Now when I am using this comma separated list to put inside an IN clause in it is throwing "ORA-01722:INVALID NUMBER" exception.

这就是我的变量的样子

l_userIds VARCHAR2(4000) := null;

这是我赋值的地方

l_userIds := getUserIds(deptId);  -- this returns a comma separated list

我的第二个查询就像 -

And my second query is like -

select * from users_Table where user_id in (l_userIds);

如果我运行这个查询,我会收到 INVALID NUMBER 错误.

If I run this query I get INVALID NUMBER error.

有人可以帮忙吗.

推荐答案

你真的需要返回一个逗号分隔的列表吗?声明一个集合类型通常会好得多

Do you really need to return a comma-separated list? It would generally be much better to declare a collection type

CREATE TYPE num_table
    AS TABLE OF NUMBER;

声明一个返回此集合实例的函数

Declare a function that returns an instance of this collection

CREATE OR REPLACE FUNCTION get_nums
  RETURN num_table
IS
  l_nums num_table := num_table();
BEGIN
  for i in 1 .. 10
  loop
    l_nums.extend;
    l_nums(i) := i*2;
  end loop;
END;

然后在您的查询中使用该集合

and then use that collection in your query

SELECT *
  FROM users_table
 WHERE user_id IN (SELECT * FROM TABLE( l_nums ));

也可以使用动态 SQL(@Sebas 演示了这一点).然而,这样做的缺点是每次调用该过程都会生成一个新的 SQL 语句,在执行之前需要再次解析该语句.它还会给库缓存带来压力,这会导致 Oracle 清除许多其他可重用的 SQL 语句,从而导致许多其他性能问题.

It is possible to use dynamic SQL as well (which @Sebas demonstrates). The downside to that, however, is that every call to the procedure will generate a new SQL statement that needs to be parsed again before it is executed. It also puts pressure on the library cache which can cause Oracle to purge lots of other reusable SQL statements which can create lots of other performance problems.

这篇关于在 IN 子句中为 NUMBER 列使用逗号分隔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Mysql目录里的ibtmp1文件过大造成磁盘占满的解决办法
ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致...
2025-01-02 数据库问题
151

按天分组的 SQL 查询
SQL query to group by day(按天分组的 SQL 查询)...
2024-04-16 数据库问题
77

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL groupwise MAX() 返回意外结果
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)...
2024-04-16 数据库问题
13

MySQL SELECT 按组最频繁
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)...
2024-04-16 数据库问题
16

在 Group By 查询中包含缺失的月份
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)...
2024-04-16 数据库问题
12