问题
I have a xls with 20000 IDs
I need to extract the rows of a table that have these IDs in Col1
Is there a clever way to do this in Oracle SQL ?
I only have a read access to this db.
I thought to slice the 20000 IDs, in order to put the first 1000 in a variable p_list1 , the next 1000 in a variable p_list2, ect and use a IN clause and union to get the whole result
But I'm not used to use paramters in my query.
Could you please review it ?
Thanks in advance for your help
DECLARE
p_list1 VARCHAR2(10) := '''id1''','''id2''','''id3''',..ect
BEGIN
execute immediate 'select * from table1 where Col1 in ('|| p_list ||')' ;
END;
回答1:
If you can create a temporary table, you can proceed in this way:
- Create temporary table
- Re-write your query with an EXISTS clause, as follow:
SELECT *
FROM table1
WHERE EXISTS(select 1 from temp_table tt WHERE tt.id = table1.Col1)
回答2:
One handy workaround is to use a list of tuples instead of a list of values. For whatever reason, Oracle allows more than 2000 tuples in a in
condition, while it disallows more than 2000 values.
So:
declare
p_list clob := '(1, ''id1''), (1, ''id2''), (1, ''id3'')';
begin
execute immediate 'select * from table1 where (1, col1) in ('|| p_list ||')' ;
end;
/
Note that I changed the p_list
parameter to a CLOB; if it is going to contain more than 2000 values, that's probably more than 4000 bytes. I also fixed the single quotes sequence.
This stills leaves you with an injection problem, if your paramaters come from outside your code: in that case, you really want to use a prepared statement rather than execute immediate
(the same logic can be used, though).
来源:https://stackoverflow.com/questions/64592537/sql-in-clause-with-20000-values