2012-11-28 94 views
0

我有這樣的所有行從表中選擇值選取場:從表中的所有領域

select distinct SCHM_CODE, 
     sum(DEP_AMT) as AMOUNT 
    from DLY_DEP_VIEW 
where Schm_code in (select SCHM_CODE 
         from DLY_DEP_VIEW) 
group by schm_code 

我會根據用戶輸入服用輸入,我不想在select語句括號,我需要爲所有有返回值,如:

select distinct SCHM_CODE, 
     sum(DEP_AMT) as AMOUNT 
    from DLY_DEP_VIEW 
where Schm_code in (ALL_SCHM_CODES) 
group by schm_code 

這是給我無效的:(編輯)

select distinct SCHM_CODE, 
     sum(DEP_AMT) as AMOUNT 
    from DLY_DEP_VIEW 
where Schm_code in (select regexp_substr('" + c + "', '[^,]+',1,level) p 
      from dual t 
     connect by level <= regexp_count('" + c + "', ',') + 1 
) 
group by schm_code; 

由於括號中的值在我的應用程序中不斷變化。達到此目的的最佳方法是什麼?該查詢在Java代碼中。

+0

如果你能得到你必須將它傳遞給查詢莫名其妙用戶輸入?你如何得到這個輸入,你存儲哪些數據結構以及如何將它傳遞給查詢? – Ben

+0

我得到它作爲字符串並將它傳遞給像查詢:'選擇不同SCHM_CODE,總和(DEP_AMT)從DLY_DEP_VIEW其中SCHM_CODE在(「‘+字符串+’」)GROUP BY SCHM_CODE' – ErrorNotFoundException

+0

所以basicly你不AMOUNT在查詢中記錄一個IN語句? – Jester

回答

1

你可以嘗試這樣的事情:

select distinct SCHM_CODE, 
     sum(DEP_AMT) as AMOUNT 
    from DLY_DEP_VIEW 
where Schm_code in (select regexp_substr(:your_string, '[^,]+',1,level) p 
      from dual t 
     connect by level <= regexp_count(:your_string, ',') + 1 
) 
group by schm_code 

:your_string是你得到了來自用戶的輸入,可以包含一個值或多個字符串(用逗號隔開)

Here is a sqlfiddle demo

BTW,使用預準備語句綁定變量,不正好連接輸入字符串。
更多here

+0

我在'regexp_substr'和'regexp_count'上獲得了Inavalid標識符# – ErrorNotFoundException

+0

@Stanley,你用你的字符串替換了':your_string'嗎? –

+0

@Stanley ,我添加了演示 –

0

可以使用嵌套表,作爲方法之一:

  • 創建嵌套表類型。假設有人提出,Schm_code是數字數據類型。

    SQL> create or replace type t_list as table of number 
        2/
    
    Type created 
    
  • 重寫查詢如下。如果列表是一個字符串列表,然後在列表中的每個元素都必須用單引號括:

    select distinct SCHM_CODE, 
         sum(DEP_AMT) as AMOUNT 
        from DLY_DEP_VIEW 
        where Schm_code in (Select column_value 
             from table(t_list(<<your list of codes>>))) 
        group by schm_code 
    

在這個例子中,爲示範起見,在SQL * Plus已被用來執行查詢和元素已經被手動鍵入:

SQL> select first_name 
    2  , last_name 
    3 from employees t 
    4 where t.employee_id in (select column_value 
    5        from table(t_list(&list)) 
    6       ); 
Enter value for list: 100,200 
old 5:       from table(t_list(&list)) 
new 5:       from table(t_list(100,200)) 

FIRST_NAME   LAST_NAME             
-------------------- -------------------------         
111     King              
Jennifer    Whalen              

SQL> select first_name 
    2  , last_name 
    3 from employees t 
    4 where t.employee_id in (select column_value 
    5        from table(t_list(&list)) 
    6       ); 
Enter value for list: 110,300,220 
old 5:       from table(t_list(&list)) 
new 5:       from table(t_list(110,300,220)) 

FIRST_NAME   LAST_NAME             
-------------------- -------------------------         
John     Chen