我會盡力解釋這一點,我有一系列產品 ['VALUE1','VALUE2']
我的表有這個資料作為例子
假設值是
| product_id | 訂購數量 |
|---|---|
| 價值1 | 5 |
| 價值2 | 3 |
如果 product_id 等于 VALUE1 和 VALUE2,我如何構建一個 select 陳述句來檢查表,但是如果陣列包含 VALUE3 它回傳 false 否則它是真的,我知道使用函式會更好。
uj5u.com熱心網友回復:
我是這樣理解的。
SQL> set serveroutput on;
樣品表:
SQL> select * from product;
PRODUC ORDER_QTY
------ ----------
VALUE1 5
VALUE2 3
PL/SQL 代碼;它將表中的值與集合的內容相交。如果該結果等于集合中值的數量,則結果為 TRUE:
SQL> declare
2 l_arr sys.odcivarchar2list := sys.odcivarchar2list();
3 l_cnt number;
4 begin
5 l_arr.extend;
6 l_arr(1) := 'VALUE1';
7 l_arr.extend;
8 l_arr(2) := 'VALUE2';
9
10 select count(*)
11 into l_cnt
12 from (select product_id from product
13 intersect
14 select column_value
15 from table(l_arr)
16 );
17 dbms_output.put_line(l_cnt);
18 if l_cnt = l_arr.count then
19 dbms_output.put_line('Result is TRUE');
20 else
21 dbms_output.put_line('Result is FALSE');
22 end if;
23 end;
24 /
2
Result is TRUE
PL/SQL procedure successfully completed.
如果我們添加VALUE3到集合中怎么辦?結果為 FALSE。
SQL> declare
2 l_arr sys.odcivarchar2list := sys.odcivarchar2list();
3 l_cnt number;
4 begin
5 l_arr.extend;
6 l_arr(1) := 'VALUE1';
7 l_arr.extend;
8 l_arr(2) := 'VALUE2';
9 l_arr.extend;
10 l_arr(3) := 'VALUE3';
11
12 select count(*)
13 into l_cnt
14 from (select product_id from product
15 intersect
16 select column_value
17 from table(l_arr)
18 );
19 if l_cnt = l_arr.count then
20 dbms_output.put_line('Result is TRUE');
21 else
22 dbms_output.put_line('Result is FALSE');
23 end if;
24 end;
25 /
Result is FALSE
PL/SQL procedure successfully completed.
SQL>
uj5u.com熱心網友回復:
SELECT
CASE WHEN
COUNT(CASE WHEN PRODUCT_ID IN ('VALUE1','VALUE2') THEN 1 END) = COUNT(*)
THEN 'TRUE' ELSE 'FALSE'
END CHK
FROM T;
或者您可以只比較集合(嵌套表):
create table t_product as
select 'VALUE1' product_id from dual union all
select 'VALUE2' product_id from dual union all
select 'VALUE3' product_id from dual;
declare
type string_table is table of t_product.product_id%type;
arr_input string_table:=string_table('VALUE1','VALUE2');
tab_data string_table;
begin
select product_id bulk collect into tab_data from t_product;
if tab_data = arr_input
then
dbms_output.put_line('yes');
else
dbms_output.put_line('no');
end if;
end;
/
或者:
select
case
when sys.ku$_vcnt('VALUE1','VALUE2') = X
then 'true'
else 'false'
end chk
from (select cast(collect(cast(product_id as varchar2(4000))) as sys.ku$_vcnt) x from t_product);
注意:最好創建和使用自己的型別而不是 sys.ku$_vcnt,例如:
create or replace type varchar2_table as table of varchar2(4000);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/421773.html
標籤:
