2017-01-17 20 views

回答

4

的東西,只有使用標準的SQL,並且將在所有RDBMS工作:

select c from t 
where replace(replace(replace(c, '1', ''), '2', ''), '3', '') = '' 
and length(c) > 0 

對於那些支持正則表達式,如Postgres的:

select c from t 
where c rlike '^[123]+$' 

甲骨文:

select c from t 
where regexp_like(c,'^[123]+$'); 
+0

的OP * *是使用Oracle。有什麼機會? :D – GurV

+0

我相信標準的SQL無法在Oracle中工作,由於null問題 – Aleksej

+0

@alek它將工作。如果該列爲空,則替換的結果將爲空,這將*不*爲「真」 – Bohemian

0

只需指出標準SQL解決方案可能無法在Oracle中正常工作。

有了這樣的表:

create table t(c) as (
       select '1233' from dual union all 
       select '1XX3' from dual union all 
       select 'XX' from dual union all 
       select ''  from dual 
      ) 

的標準方法得出:

SQL> select c from t 
    2 where replace(replace(replace(c, '1', ''), '2', ''), '3', '') = '' 
    3 and c <> ''; 

no rows selected 

的原因是在路上的Oracle處理空字符串:

SQL> select c, 
    2   case when replace(replace(replace(c, '1', ''), '2', ''), '3', '') = '' and c <> '' then 'MATCH' 
    3    else 'NO MATCH' 
    4   end as checkMatch 
    5 from t; 

C CHECKMAT 
---- -------- 
1233 NO MATCH 
1XX3 NO MATCH 
XX NO MATCH 
    NO MATCH 

在簡單例如:

SQL> select case when '' = '' then 'true' else 'false' end 
    2 from dual; 

CASEW 
----- 
false 

在Oracle中,檢查應針對NULL

SQL> select c, 
    2   case when replace(replace(replace(c, '1', ''), '2', ''), '3', '') is null and c is not null then 'MATCH' 
    3    else 'NO MATCH' 
    4   end as checkMatch 
    5 from t; 

C CHECKMAT 
---- -------- 
1233 MATCH 
1XX3 NO MATCH 
XX NO MATCH 
    NO MATCH 

因此,沒有正則表達式的Oracle解決方案可能是:

SQL> select c from t 
    2 where replace(replace(replace(c, '1', ''), '2', ''), '3', '') is null 
    3 and c is not null; 

C 
---- 
1233