2013-07-22 72 views
0

我是DB2查詢的新手。在存儲過程中將逗號分隔值作爲IN參數傳遞

在這裏,我傳遞一個逗號分隔值作爲存儲過程中的IN參數。我想根據這些價值進行搜索。

Select * from USER where user_id in (IN_User); 

這裏,IN_User會有那種( 'VAL1', '值2', 'VAL3')

應該返回所有具有VAL1或VAL2或VAL3作爲USER_ID行的值。儘管我知道這可以使用UDF完成,但是我想知道是否有其他方法可以在沒有UDF的情況下完成。

+0

我覺得@Maya可能有[一些見解這裏。](http://stackoverflow.com/questions/17784348/how-to-pass-string-or-list-as-a-input-parameter-for-in-clause-in-db -2-stored-pro) – mustaccio

+0

你不喜歡沒有三個價值;你有一個20字節的值。 SQL語句無法知道您不希望它被視爲單個值。創建建議的函數或使用構造的動態SQL語句。 – user2338816

回答

2

請創建一個函數來拆分逗號分隔字符串

請參閱下面的功能

CREATE FUNCTION StringToRows(
    cString1 CLOB (10 M) , 
    cStringSplitting1 VARCHAR(10)) 
RETURNS TABLE (Lines VARCHAR(500)) 
SPECIFIC StringToRows_Big 
DETERMINISTIC 
NO EXTERNAL ACTION 
CONTAINS SQL 
BEGIN ATOMIC 
DECLARE cStringSplitting VARCHAR(10); 
DECLARE LenSplit SMALLINT; 
SET cStringSplitting = cStringSplitting1; 
SET LenSplit = LENGTH(cStringSplitting); 

IF LENGTH(TRIM(cStringSplitting)) = 0 THEN 
    SET cStringSplitting = ' ', LenSplit = 1 ; 
END IF ; 

RETURN WITH 
    TEMP1 (STRING) as (values (cString1)), 
    TEMP2 (Lines, STRING_left) as 
    (SELECT 
    SUBSTR(STRING,1, CASE WHEN LOCATE(cStringSplitting, STRING) = 0 THEN LENGTH(STRING) ELSE LOCATE(cStringSplitting,STRING) - 1 END), 
    (CASE WHEN (LOCATE(cStringSplitting, STRING) = 0) THEN '' ELSE SUBSTR(STRING, LOCATE(cStringSplitting,STRING) + LenSplit) END) 
    FROM TEMP1 WHERE LENGTH(STRING) > 0 
    UNION ALL 
    SELECT 
    SUBSTR(STRING_left,1, CASE LOCATE(cStringSplitting,STRING_left) WHEN 0 THEN LENGTH(STRING_left) ELSE LOCATE(cStringSplitting,STRING_left) - 1 END), 
    (CASE WHEN LOCATE(cStringSplitting,STRING_left) = 0 THEN '' ELSE SUBSTR(STRING_left, LOCATE(cStringSplitting,STRING_left) + LenSplit) END) 
    FROM TEMP2 WHERE LENGTH(STRING_left) > 0) 
    SELECT Lines FROM TEMP2; 
END 

請參閱樣本存儲過程調用的函數

CREATE PROCEDURE TEST_USR(IN @inputParam CLOB (10 M)) 
SPECIFIC TEST_USR 
DYNAMIC RESULT SETS 1 
P1: BEGIN 
    DECLARE CURSOR1 CURSOR WITH RETURN FOR 
      Select * from USER where user_id IN (SELECT * FROM TABLE(StringToRows(@inputParam, ',')) AS test); 
    OPEN CURSOR1; 
END P1 
+0

非常感謝,完美的作品 –

相關問題