2014-03-05 29 views
0

我有一個使用動態查詢的過程(請參見下文)。我想用動態查詢重寫這個過程。我如何寫下面的條件?Oracle SQL - 動態查詢的替代方案

PROCEDURE DemoProcedure(p_firstname IN VARCHAR2, 
         p_lastname IN VARCHAR2, 
         p_phone  IN VARCHAR2 
         o_Cursor  OUT t_Cursor) IS 

SQLString VARCHAR2(4000); 

BEGIN 

    SQLString := 
     'SELECT * FROM 
     SCHEMA.TABLENAME_a A 
     INNER JOIN SCHEMA.TABLENAME_b B 
     ON A.ID = B.ID 
     WHERE 
     A.TYPE = 1 '; 

    IF p_firstname IS NOT NULL THEN 
     SQLString := SQLString || ' and UPPER(A.FIRST_NAME) like UPPER(''' || p_firstname || ''')'; 
    END IF; 

    IF p_lastname IS NOT NULL THEN 
     SQLString := SQLString || ' and UPPER(A.LAST_NAME) like UPPER(''' || p_lastname || ''')'; 
    END IF; 

    IF p_phone IS NOT NULL THEN 
     SQLString := SQLString || ' and UPPER(A.PHONE) = ''' || 
          p_phone || ''''; 
    END IF; 

     SQLString := SQLString || ' order by a.id '; 

     OPEN o_Cursor FOR SQLString; 

END DemoProcedure; 
+0

你可以試試老 「(p_phone不是null,UPPER(A.PHONE)= p_phone)」? – jean

+1

以大寫形式存儲名字和姓氏或者在相關列上定義基於函數的索引是個好主意。 –

+2

如果這是一個大表,它可能值得作爲一個動態查詢,或有多個SQL語句,而不是一個單一的catch-all。原因在於如果您有一組'xx IS NULL OR xx = col_xx'語句,Oracle將無法找到正確的索引。只有「last_name」搜索的右側索引與「first_name」唯一搜索不同。但是,你絕對應該學習如何在動態sql中使用綁定變量。 –

回答

3

看起來你只是想

OPEN o_cursor 
FOR SELECT ... 
     WHERE A.TYPE = 1 
     AND (p_firstname IS NULL or upper(a.first_name) = upper(p_firstname)) 
     AND (p_lastname IS NULL or upper(a.last_name) = upper(p_lastname)) 
     AND (p_phone  IS NULL or upper(a.phone)  = p_phone) 
     ORDER BY a.id 

我不知道爲什麼你要打擾上層套管電話number--你有一個電話號碼字符數據?

+0

抱歉,在爲郵件準備SQL時出現錯誤。 – CoolArchTek

2

不同的方式編寫相同的SQL作爲@JustinCave建議 -

OPEN o_cursor 
FOR SELECT ... 
     WHERE A.TYPE = 1 
     AND upper(a.first_name) = nvl(upper(p_firstname), upper(a.first_name)) 
     AND upper(a.last_name) = nvl(upper(p_lastname),upper(a.last_name)) 
     AND upper(a.phone)  = nvl(p_phone,upper(a.phone)) 
     ORDER BY a.id 
+1

+1由於在NVL周圍進行了一些Oracle優化,因此此方法運行得比其他答案快得多。有關詳細信息,請參見[Jonathan Lewis的文章](http://jonathanlewis.wordpress.com/2007/01/09/conditional-sql/)。 –