SQL stmt连接(sp *)

时间:2011-09-19 19:08:39

标签: sql plsql

本周我正在做一些SQL工作,我通常会写Java。

我需要在我的SQL中添加一些if,但是不想进行任何字符串连接。

这应该很简单:我只是不知道SQL语法

我想把所有那些“AND”语句“if”条件用于我传入的参数

我是否必须这样做:

     IF p_sac IS NOT NULL
 THEN
    stmt := stmt || ' AND nsns.sac = ''' || p_sac || '''';
 END IF;

 IF p_value1 IS NOT NULL
 THEN                                                        
    stmt := stmt || ' AND UPPER(value1s.value1) LIKE ''' || UPPER(p_value1) || ''' ';
 END IF;

或者上面有替代方案吗?

基本上我有这个:

FUNCTION summarize_item_search_data (p_obj_code IN VARCHAR2,  p_value1 IN VARCHAR2,
                                                               p_sac IN NUMBER,    p_job_type_id    IN NUMBER,
                                                               p_value4 IN NUMBER)
  RETURN sys_refcurvalue2
  IS
  result_cur   sys_refcurvalue2;  
BEGIN

     OPEN result_cur FOR

       SELECT DISTINCT jp.id, jp.row_top.mwslin AS mwslin, jp.obj_code, jp.jobload_year, jp.row_top.fiscal_year AS fiscal_year,
                                      nsns.sac, value1s.value1, nsns.nsn,
         DECODE( jp.row_top.nsn_id, NULL, jp.row_top.nomenclature ,nsns.nomenclature) AS nomenclature, jp.row_top.value4 AS value4
        FROM scabs sch, jobs JP, master_nsn nsns, master_value1 value1s, TABLE(value1s.group_id) (+) ntab, 
                 groups pgds
  WHERE jp.row_top.nsn_id = nsns.id(+) AND nsns.value1_id = value1s.id(+)
-- stmt := stmt || ' AND ''' || p_year || ''' = ntab.fiscal_year(+)';
        AND ntab.group_id = pgds.id(+)    
        AND nsns.sac = p_sac
        AND UPPER(value1s.value1) LIKE UPPER(p_value1) 
        AND UPPER(jp.obj_code) = UPPER(p_obj_code)
        AND jp.row_top.value4 <=   p_value4
        AND jp.row_top.job_type_id =p_job_type_id


  RETURN result_cur;
  END summarize_item_search_data;

1 个答案:

答案 0 :(得分:2)

将条件全部放入WHERE条款:

WHERE
    (p_sac IS NULL OR nsns.sac = p_sac) AND
    ....

如果性能受到很大影响,那么您可能需要考虑使用动态SQL,但我会从上面的方法开始。