PLSQL:CASE结果中的多个值

时间:2018-08-02 23:35:08

标签: plsql case

我正在为PLSQL查询based on this answer(以及许多其他喜欢的查询)动态设置要排序的列。我想添加一个默认情况,它在三列上排序。

这是我的尝试:

 int id = Convert.ToInt32(comboBox_Degree.SelectedValue.GetHashCode());

一切正常,但我想指定要排序的那三列。

使用-- ... long SQL query -- ps_global_order is the column to sort on, passed in to stored procedure. -- ps_global_order_dir is the direction to sort on, similarly passed in. order by case -- this does not compile (00905 missing keyword): when ps_global_order is null then name, phone, email -- this compiles, but I need it on the three columns: -- when ps_global_order is null then name end, case when ps_global_order_dir <> 'ASC' then '' when ps_global_order like 'name' then name end, case when ps_global_order_dir <> 'ASC' then '' when ps_global_order like 'phone' then phone end, case when ps_global_order_dir <> 'ASC' then '' when ps_global_order like 'email' then email end, case when ps_global_order_dir <> 'DESC' then '' when ps_global_order like 'name' then name end, case when ps_global_order_dir <> 'DESC' then '' when ps_global_order like 'phone' then phone end, case when ps_global_order_dir <> 'DESC' then '' when ps_global_order like 'email' then email end 语句是否可行?我必须诉诸动态SQL还是缺少解决方法?

2 个答案:

答案 0 :(得分:1)

这样做:

-- ... long SQL query
--      ps_global_order is the column to sort on, passed in to stored procedure.
--      ps_global_order_dir is the direction to sort on, similarly passed in. 
order by 
  case 
    when ps_global_order is null then name
    else null
  end,
  case
    when ps_global_order is null then phone
    else null
  end,
  case
    when ps_global_order is null then email
    else null
  end,
  case
    when ps_global_order_dir <> 'ASC' then null
    when ps_global_order like 'name' then name
  end,
  case
    when ps_global_order_dir <> 'ASC' then null
    when ps_global_order like 'phone' then phone
  end,
  case
    when ps_global_order_dir <> 'ASC' then null
    when ps_global_order like 'email' then email
  end,
  case
    when ps_global_order_dir <> 'DESC' then null
    when ps_global_order like 'name' then name
  end,
  case
    when ps_global_order_dir <> 'DESC' then null
    when ps_global_order like 'phone' then phone
  end,
  case
    when ps_global_order_dir <> 'DESC' then null
    when ps_global_order like 'email' then email 
  end

请注意,我已经用''替换了所有NULL的情况,这更加清楚了IMO。

答案 1 :(得分:0)

我讨厌这么快回答自己的问题,但我发现了:

order by 
    case  when nvl(ps_global_order, ' ') = ' ' then name end,
    case  when nvl(ps_global_order, ' ') = ' ' then phone end,
    case  when nvl(ps_global_order, ' ') = ' ' then email end,
    case
        when ps_global_order_dir <> 'ASC' then ''
    -- continues...

This answer是非常有用的帮助,但它已被Google搜索结果所掩盖。但是,这如何在没有逗号的情况下无法工作。