简体   繁体   English

如何使用servlet和jsp获取Null值查询表达式

[英]How to take Null values query expression using servlet and jsp

I need to calculate and retrieve data from SQL server database table in my table having the NoOfErrors and NoOfAudited columns. 我需要在具有NoOfErrorsNoOfAudited列的表中的SQL server数据库表中计算和检索数据。

I need to calculate the Accuracy based on these columns. 我需要根据这些列计算准确度。

I have a query like this 我有这样的查询

select 
   a.id, 
   (100-((a.NoOfErrors*100)/ NULLIF(a.NoOfAudited,0))) as Accuracy 
from Table1 a 
 join Table2 pd 
   on a.batchid=pd.id 
where 
  a.charge='"+Poster+"' and status=1 

The above query is executed only when the NoOfErrors and NoOfAudited columns contain some values. 仅当NoOfErrorsNoOfAudited列包含某些值时, NoOfErrors执行上述查询。

I have all the values but if a value in any one of the NoOfErrors and NoOfAudited columns contains Null value it doesn't retrieve any data, and it shows No data found . 我有所有的值但是如果任何一个NoOfErrorsNoOfAudited列中的值包含Null值,它不会检索任何数据,并且它显示No data found

ResultSet data is not accepting null values ResultSet数据不接受空值

How can I make the query accept null values and retrieve data by replacing null to empty in jsp table? 如何通过在jsp表中将null替换为空来使查询接受空值并检索数据?

This line is problematic and should be corrected. 这条线存在问题,应予以纠正。

   (100-((a.NoOfErrors*100)/ NULLIF(a.NoOfAudited,0))) as Accuracy 

problem #1 : 问题#1

NULLIF(a.NoOfAudited,0)

if NoOfAudited is NULL then the expression will return 0 ; 如果NoOfAuditedNULL则表达式将返回0 ; basically you are dividing by zero. 基本上你除以零。 This should be replaced with 1 like below 这应该替换为1如下所示

NULLIF(a.NoOfAudited,1)

problem #2 问题#2

No checks for NULL value for NoOfErrors column. 不检查NoOfErrors列的NULL值。 In SQL server most NULL arithmetic results in NULL . 在SQL Server中,大多数NULL算法都会产生NULL For example all below queries will yield NULL 例如,以下所有查询都将产生NULL

select 100-NULL*100/0
select NULL*100
select NULL/0
select 100-NULL

Therefore you'll get NULL value as Accuracy whenever NoOfErrors is NULL 因此,只要NoOfErrorsNULL您将获得NULL值作为Accuracy

To correct this part, you should write your query expression like 要更正此部分,您应该编写查询表达式,如

   (100-((COALESCE(a.NoOfErrors,0)*100)/ COALESCE(a.NoOfAudited,1))) as Accuracy 

Note that I've replaced NULLIF with COALESCE which is ANSI compliant and will run on both SQL server and MySQL 请注意,我已经将NULLIF替换为符合ANSI标准的COALESCE ,并且将在SQL服务器和MySQL上运行

TLDR; TLDR;

your query should be like 你的查询应该是这样的

select 
   a.id, 
  case 
   when COALESCE(a.NoOfErrors,a.NoOfAudited,'') ='' 
   then''
   else 
    CAST((100-((COALESCE(a.NoOfErrors,0)*100)/ COALESCE(a.NoOfAudited,1))) as VARCHAR(10))as Accuracy
 end
from Table1 a 
 join Table2 pd 
   on a.batchid=pd.id 
where 
  a.charge='"+Poster+"' and status=1 

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

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