[英]Oracle 12c - dynamically generate a where clause based on a value in a different table
我正在嘗試編寫如下的Oracle 12c SQL語句:
select * from table1 where col1 in (*dynamicvalue*)
我希望動態值是以下SQL的結果:
select col2 from table2 where rowid = 1
這可能嗎? Col2包含一個類似這樣的值的列表:'val1','val2','val3'
謝謝
您可以拆分字符串並執行查詢,而不是dynamic-sql。 要分割字符串,請使用regexp_substr
。
select * from table1
where col1 in (select regexp_substr(col2,'[^,]+', 1, level)
from table2
connect by regexp_substr(col2, '[^,]+', 1, level) is not null)
為什么不這樣做呢?
select t1.*
from table1 t1
where t1.col1 in (select col2 from table2 where rowid = 1);
編輯:
在單列中存儲值列表是一個壞主意,以至於我錯誤地解釋了這個問題。 我將“值列表”作為存儲在不同行中的值。 為什么? 因為那是存儲數據的正確方法。 將列的列表存儲在帶分隔符的列表中不是SQLish。
就是說,有時我們會陷入別人的錯誤設計決定中。 如果您處於這種情況,則可以使用這樣的查詢:
select t1.*
from table1 t1
where exists (select 1
from table2 t2
where rowid = 1 and
',' || t2.col2 || ',' like '%,' || t1.col1 || ',%'
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.