简体   繁体   English

为什么常规语句在DB2中有效,但我的准备语句却不起作用?

[英]Why my prepared statement doesn't work, while regular statement work in DB2?

I have a strange behavior when I try to use a following query with PreparedStatement 当我尝试对PreparedStatement使用以下查询时,我有一个奇怪的行为

Query itself is following: 查询本身如下:

SELECT 
    CASE  
        WHEN TYPE LIKE '%Linux%' THEN 'Linux' 
        ELSE 'UNKNOWN'
    END AS OS, 
COUNT(*) AS TOTAL 

FROM COMPUTERS.OS 

GROUP BY 
    CASE   
        WHEN TYPE LIKE '%Linux%' THEN 'Linux'
        ELSE 'UNKNOWN' 
    END

And it works well. 而且效果很好。 But when I create query like following: 但是当我创建如下查询时:

SELECT 
    CASE  
        WHEN TYPE LIKE ? THEN ?
        ELSE 'UNKNOWN'

    END AS OS, 
COUNT(*) AS TOTAL 

FROM COMPUTERS.OS 

GROUP BY 
    CASE   
        WHEN TYPE LIKE ? THEN ? 
        ELSE 'UNKNOWN'
    END

And set it accordingly 并据此进行设置

String os = "Linux";
ps.setString(1, "%" +  os  + "%");
ps.setString(2, os);
ps.setString(3, "%" +  os  + "%");
ps.setString(4, os);

It doesn't work and throw a following error: 它不起作用并引发以下错误:

SQLCODE=-119, SQLSTATE=42803, SQLERRMC=TYPE A column reference in the SELECT or HAVING clause is invalid, because it is not a grouping column; SQLCODE = -119,SQLSTATE = 42803,SQLERRMC = TYPE SELECT或HAVING子句中的列引用无效,因为它不是分组列; or a column reference in the GROUP BY clause is invalid. 或GROUP BY子句中的列引用无效。

Somebody can me explain please what's wrong with my PreparedStatement? 有人可以解释一下我的PreparedStatement是什么问题吗?

Thank you. 谢谢。

This might have to do with parameters and how DB2 determines if the group by clause is identical to the columns in the select . 这可能与参数以及DB2如何确定group by子句是否与select的列相同有关。 A simple work around is to use a subquery: 一个简单的解决方法是使用子查询:

SELECT OS, COUNT(*) AS TOTAL 
FROM (SELECT os.*,
             (CASE WHEN TYPE LIKE '%Linux%' THEN 'Linux' 
                   ELSE 'UNKNOWN'
              END) AS OS
      FROM COMPUTERS.OS os
     ) os
GROUP BY OS;

For the wildcard version, you would only put the wildcards in once and the compiler should accept the query. 对于通配符版本,只需将通配符放入一次,编译器应接受该查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM