SUBSTRING(COALESCE(
CASE
WHEN c.legal_type IS NULL THEN
' '
WHEN c.legal_type = 'INDIVIDL' THEN
c.ssn
ELSE c.tax_identifier
END
, ' '), 1, 9), c.birth_date,
CASE
WHEN c.legal_type IS NULL THEN
?
WHEN c.legal_type = 'INDIVIDL' THEN
c.first_name
ELSE ?
END
, c.middle_name, substring((
CASE
WHEN c.legal_type IS NULL THEN
' '
WHEN c.legal_type = 'INDIVIDL' THEN
c.last_name
ELSE c.business_name
END), 1, 25) surname, ?, c.company, c.operations_area, car.relationship_id, ?, ? FROM s_xref_e49_e30_e33 car INNER JOIN s_customer_e49 c ON car.customer_id = c.customer_id INNER JOIN s_credit_reporting_control_e23 crc ON car.relationship_id = crc.relationship_id INNER JOIN
(
SELECT car.account_id,
b.metro2_base_id
FROM s_metro2_base_e25 b
INNER JOIN s_credit_reporting_control_e23 crc
ON crc.credit_reporting_control_id = b.credit_reporting_control_id
INNER JOIN s_xref_e49_e30_e33 car
ON crc.relationship_id = car.relationship_id
WHERE b.metro2_report_id = ?
AND b.metro2_base_id >= ?
AND b.metro2_base_id <= ?) m2 ON m2.account_id = car.account_id WHERE car.relationship_type != 'PRIMARY'
AND
car.has_legal_relationship = 'Y')
trying to write query without COALESCE AND SUBSTRING AND CASE CONACT SINCE ENCRYPTON DOESNT SUPPORT THESE
Related
I need to get a very long string from Oracle DB in Spring App, but using a function returning clob leads to internal server error 500. How to get a custom query result containing Clob?
PL/SQL function returning a very long string in clob:
create or replace function getVeryLongString(id_ in number)
return clob as
CURSOR cur IS select x.TARGET || ' pX=' || x.px as tpx -- to get concat string in order of PX desc
from (
select distinct a.ID,
a.TARGET,
MAX(a.PX) OVER (PARTITION BY a.TARGET, a.ID) as px
from BA_ACTIVITYDATA A
where A.TARGET is not null
and a.ID = id_
order by px desc
) x;
l_data clob := '';
begin
FOR fld IN cur
LOOP
l_data := l_data || fld.tpx || ' | ';
end loop;
return rtrim( l_data, ' | ');
end
;
I use this function in Query in Java Spring app:
public interface TargetRepository extends JpaRepository<List, Long> {
#Query(
value = "select t1.fieldA,\n" +
" t1.fieldB,\n" +
" t2.fieldC,\n" +
" getVeryLongString(t3.value1) as fieldD\n" +
"from tableA t1\n" +
"join tableB t2 on t1.id = t2.id\n" +
"join tableC t3 on t3.id = t2.id\n" +
"where t.id = :id",
nativeQuery = true
)
DataTypePX getDataById(Long id);
}
TargetActivity interface looks like:
public interface DataTypePX {
String getFIELDA();
String getFIELDB();
String getFIELDC();
String getFIELDD();
}
Using the above code leads to 500 ERROR.
to fix it I need to change function getVeryLongString as returning varchar2 - it works, but it leads to cutting of result string only to 4000 symbols:
create or replace function getVeryLongString(id_ in number)
return varchar2 as
CURSOR cur IS select x.TARGET || ' pX=' || x.px as tpx -- to get concat string in order of PX desc
from (
select distinct a.ID,
a.TARGET,
MAX(a.PX) OVER (PARTITION BY a.TARGET, a.ID) as px
from BA_ACTIVITYDATA A
where A.TARGET is not null
and a.ID = id_
order by px desc
) x;
-- l_data varchar2(32767) := '';
l_data clob := '';
begin
FOR fld IN cur
LOOP
l_data := l_data || fld.tpx || ' | ';
end loop;
return rtrim( substr(l_data, 1, 4000), ' | ');
end;
Hi i have a long query for a spring, java 8, hibernate, mysql application, which works as expected, except the last part, which sums the reserved items in store:
SELECT new example.package.RaktarKimutatasDTO(rk.cikkId.cikkName,
CONCAT(SUM(rk.mennyisegMe1),' ', rk.me1.unitCode, ' / ', SUM(rk.mennyisegMe2),' ', rk.me2.unitCode, ' / ', SUM(rk.mennyisegMe3),' ', rk.me3.unitCode),
CONCAT(AVG(rk.listaar), ' Ft'),
CONCAT(rk.mennyisegMe1*rk.listaar, ' Ft'),
rk.raktarId.raktarNeve, rk.cikkId.vtsz.vatCode,
SUM(CASE WHEN rk.vevoiEntity IS NOT NULL THEN rk.mennyisegMe1 ELSE 0.0 END))
FROM RaktarkeszletEntity rk
WHERE rk.raktarId.identifier IN ?1 AND rk.createDate<?2 AND (rk.bejovoszamlaEntity LIKE 'RB%' OR (rk.bejovoszamlaEntity LIKE 'BM%' AND rk.bevetel = TRUE))
GROUP BY rk.cikkId
The problem is, the SUM(CASE... ) part is always returns 0.
While if i use the (nearly) same query in in plain SQL, from Mysql workbench, it works as expected, sums the quantities for items which have "vevoiEntity" which is not null (so the reserved quantity).
vevoiEntity field in DB has int type, which can be null too.
The fields, called entity (except of course which used at FROM) are not entities, but simple integer. (previous developer had problems with naming too).
I've tried using more parentheses, tried " <> NULL" tried "vevoiEntity>0", etc but nothing helped, the case is always false, every other parts are perfect.
Why does it works differently in native SQL, and JPQL? I set hibernate.show_sql=true, and i saw that the generated query for the SUM CASE part, is just like the query that i used in workbench, so the translation seems to be ok.
plain SQL, (already working parts are left out) which works:
SELECT rk.cikk_id, SUM(CASE WHEN rk.vevoi_tetel_id IS NOT NULL THEN rk.mennyiseg_me_1 ELSE 0 END) as reserved FROM nast_raktarkeszlet rk GROUP BY rk.cikk_id;
or:
SELECT rk.cikk_id, CONCAT(SUM(rk.mennyiseg_me_1),' ', rk.me_1, ' / ', SUM(rk.mennyiseg_me_2),' ', rk.me_2, ' / ', SUM(rk.mennyiseg_me_3),' ', rk.me_3), CONCAT(AVG(rk.listaar), ' Ft'), CONCAT(rk.mennyiseg_me_1*rk.listaar, ' Ft'), rk.raktar_id, rk.cikk_id, SUM(CASE WHEN IFNULL(rk.vevoi_tetel_id, 0) >0 THEN rk.mennyiseg_me_1 ELSE 0 END) FROM nast_raktarkeszlet rk GROUP BY rk.cikk_id
generated query:
select
basecikkek1_.cikk_name as col_0_0_,
concat(sum(rak0_.mennyiseg_me_1),
' ',
men2_.unit_code,
' / ',
SUM(rak0_.mennyiseg_me_2),
' ',
men3_.unit_code,
' / ',
SUM(rak0_.mennyiseg_me_3),
' ',
men4_.unit_code) as col_1_0_,
concat(avg(rak0_.listaar),
' Ft') as col_2_0_,
concat(rak0_.mennyiseg_me_1*rak0_.listaar,
' Ft') as col_3_0_,
rak5_.raktar_name as col_4_0_,
vts7_.vat_code as col_5_0_,
sum(case
when rak0_.szallitolevel_tetel_id is not null
or rak0_.kimeno_tetel_id is not null
or rak0_.vevoi_tetel_id<>0 then rak0_.mennyiseg_me_1
else 0
end) as col_6_0_
from
nast_raktarkeszlet rak0_ cross
join
nast_cikkek basecikkek1_ cross
join
nast_vtsz vts7_ cross
join
nast_units men2_ cross
join
nast_units men3_ cross
join
nast_units men4_ cross
join
nast_raktarak rak5_
where
rak0_.cikk_id=basecikkek1_.id
and basecikkek1_.vtsz=vts7_.id
and rak0_.me_1=men2_.id
and rak0_.me_2=men3_.id
and rak0_.me_3=men4_.id
and rak0_.raktar_id=rak5_.id
and (
rak0_.raktar_id in (
? , ? , ? , ?
)
)
and rak0_.create_date<?
and (
rak0_.parentid like 'RB%'
or (
rak0_.parentid like 'BM%'
)
and rak0_.bevetel=1
)
group by
rak0_.cikk_id
OMG my bad. The WHERE conditions are exclude the records that have non null "vevoientity"
My query is
sql = "SELECT pmmr.REQUEST_NO , pmel.event_datetime Event_Datetime,Pmmr.Form_No Form_No, nvl(Pmf.Form_Name, Pmmr.Form_No) formName, pmmr.MRN, nvl (p.FIRST_NAME || DECODE(p.FAMILY_NAME, NULL, '', ' ' || p.FAMILY_NAME),pmmr.MRN) PATIENT_NAME,pmmr.ASSIGNED_TO,"
+" pmmr.DRUG_GENERIC_NAME,pmmr.LAST_STATUS, nvl(initcap(( hr1.FIRST_NAME || ' ' || hr1.LAST_NAME)),pmmr.LAST_PERFORMER_ID) LastActionBy,"
+" nvl(hr2.DEPARTMENT || ' - ' || hr2.SECTION_NAME,'') ORGANIZATION_UNIT, nvl(initcap(( hr2.FIRST_NAME || ' ' || hr2.LAST_NAME)),pmmr.REQUESTER_ID) RequesterName, pmmr.REQUEST_DATE,"
+" pmmr.item_cost"
+" FROM PHRM_MFRP_MEDICATION_REQUEST pmmr"
+" join PHRM_MFRP_EVENT_LOG pmel on pmmr.REQUEST_NO = pmel.REQUEST_NO"
+" left outer join Hr_Employee hr1 on Pmmr.Last_Performer_Id = Hr1.Employee_Number"
+" left outer join Hr_Employee hr2 on Pmmr.Requester_Id = Hr2.Employee_Number"
+" left outer join EAPPTMT.PATIENT p on Pmmr.Mrn = P.Mrn"
+" left outer join Phrm_Mfrp_Form pmf on Pmmr.Form_No = Pmf.Form_No";
if (status.equals("Pending")){
}
else if(status.equals("Approved")){
sql += " WHERE pmmr.BRANCH_ID = ? AND pmel.EVENT_STATUS IN ('Pharmacy Director Approved')"
+" and Pmmr.Form_No = 1";
sql +=" and pmel.event_datetime >= (?,'dd/MM/yyyy') and pmel.event_datetime <= (?,'dd/MM/yyyy')";
sql+=" order by LAST_STATUS, EVENT_DATETIME DESC ";
} else if(status.equals("Disapproved")){
sql += " WHERE pmmr.BRANCH_ID = ? AND pmel.EVENT_STATUS IN ('Pharmacy Director Disapproved')"
+ "and Pmmr.Form_No = 1";
sql +=" and pmel.event_datetime >= (?,'dd/MM/yyyy') and pmel.event_datetime <= (?,'dd/MM/yyyy')";
sql+=" order by LAST_STATUS, EVENT_DATETIME DESC ";}
stmt = Con.prepareStatement(sql);
stmt.setString(2, startDate);
stmt.setString(3, endDate);
//tmt.setString(3, status);
stmt.setInt(1, branchId);
rs = stmt.executeQuery();
I get the error java.sql.SQLSyntaxErrorException: ORA-01797: this operator must be followed by ANY or ALL whenever i run it,
What does it mean and how can I fix it ?
Your code is very messy and should be cleaned up. When asking the questions here you usually should create a MRE in which the concrete problem is highlighed, instead of pasting your whole code base here and letting us find your bugs.
Anyways since I got interested on this I spent a moment of googling and found your question already answered here.
It says the ORA-01797 is related to the query missing the to_date() constant.
From looking at your code I can see several places where it's missing like the following one:
sql +=" and pmel.event_datetime >= /*to_date missing here!*/ (?,'dd/MM/yyyy') and
pmel.event_datetime <= /*to_date missing here!*/ (?,'dd/MM/yyyy')";
Try to fix it and then it should work. Hope it'll help you
I have a native query in plsql like this;
create or replace package body DBPK_Monitoring is
PROCEDURE monitoring_Search(cur OUT SYS_REFCURSOR,) is
query VARCHAR(30000);
whereClause VARCHAR(10000);
BEGIN
whereClause := whereClause || ' and ( cnt.contract_status!=7)';
query := ' select itemTitle as "itemTitle", numberOfRow as "numberOfRow" ,
orderNumber as "orderNumber",createDate as "createDate",
priorityNumber as "priorityNumber"
from buy_buy_order bbo
inner join buy_buy_order_item bbi
on bbi.buy_order_id = bbo.id
left outer join core_User_Role shoUserRole
on shoUserRole.id = bbi.buy_Expert_Id
' || whereClause || ' order by ' || orderBy ||
') e WHERE e.rowNO> ' || lower_Bound || ' and e.rowNO<=' ||
upper_Bound;
OPEN cur FOR query
end monitoring_Search;
end DBPK_Monitoring;
I use of this query in repository with hql like this :
Session session = getSession();
Query query = session.getNamedQuery("monitoring_Search").setResultTransformer(Transformers.aliasToBean(MonitoringDto.class));
int firstResultIndex = searchOption.getPageNumber() * searchOption.getPageSize();
query.setInteger("lower_Bound", firstResultIndex);
query.setParameter("upper_Bound", firstResultIndex + searchOption.getPageSize());
query.setString("orderBy", searchOption.getOrder());
query.setParameter("buyOrderNumber", buyOrderNumber);
List<MonitoringDto> list = query.list();
int count = (list.size() > 0L) ? list.get(0).getNumberOfRow() : 0;
return new QueryResult<MonitoringDto>(searchOption.getPageNumber(), count, searchOption.getPageSize(), list);
When I run program, I get this error:
java.lang.illegalargumentexception no query defined for that name
[monitoring_Search]
How can I fix this?
you have to define monitoring_search as a Hibernate named query , you can see the detail about this in this link : https://www.baeldung.com/hibernate-named-query
have a nice day and kiss people around you ;)
I'm using SQL Case in my select and in group by clause and I'm working in JAVA. Whenever I execute my java program it says:
Column 'dbo.JOHN_Dashboard.Log_Date' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
My Query is:
SELECT EP.Site_Code AS [Site_Code], DB.[Site] AS [Site], DB.[Utility] AS [Utility],
CASE ? WHEN 'Raw' THEN dateadd(mi,datediff(mi,0,DB.[log_date]),0)
WHEN 'Hour' THEN dateadd(hh,datediff(hh,0,DB.[log_date]),0)
WHEN 'Day' THEN dateadd(dd,datediff(dd,0,DB.[log_date]),0)
WHEN 'Week' THEN dateadd(wk,datediff(wk,0,DB.[log_date]),0)
WHEN 'Month' THEN dateadd(mm,datediff(mm,0,DB.[log_date]),0)
WHEN 'Year' THEN dateadd(yy,datediff(yy,0,DB.[log_date]),0)
ELSE DB.[log_date]
END AS [log_date],
SUM(CASE WHEN DB.[value] >= 0 THEN DB.[value] ELSE 0 END) AS [value],
SUM(CASE WHEN DB.[Cost] >=0 THEN DB.[cost] ELSE 0 END) AS [Cost],
SUM(CASE WHEN DB.[CO2] >=0 THEN DB.[CO2] ELSE 0 END) AS [CO],
MT.[Meter_type_name] AS [Meter Type],
MN.[Meter_Name] AS [Meter Name],
U.[Unit_Name] AS [Units],
EP.EnergyPoint_ID AS [Meter_ID],
EP.Parent_ID AS [Parent],
EP.Meter_Description AS [Meter_Description]
FROM [dbo].[JOHN_Dashboard] DB
INNER JOIN [dbo].[EnergyPoints] EP ON DB.[EnergyPoint_ID] = EP.[EnergyPoint_ID]
INNER JOIN [dbo].[Meter_Types] MT ON MT.[Meter_Type_ID] = EP.[Meter_Type_ID]
INNER JOIN [dbo].[Meter_Names] MN ON MN.[Meter_Name_ID] = EP.[Meter_Name_ID]
INNER JOIN [dbo].[Units] U ON U.[Unit_ID] = EP.[Unit_id]
WHERE [log_date] >= ? AND [Log_Date] < DATEADD(DAY, 1, ?)
AND ( ? IS NULL OR EP.Energypoint_ID = ?)
GROUP BY EP.Site_Code, DB.[Site], DB.[Utility], MT.[Meter_type_name],
MN.[Meter_Name], U.[Unit_Name], EP.[EnergyPoint_ID],
EP.[Parent_ID], EP.[Meter_Description],
CASE ? WHEN 'Raw' THEN dateadd(mi,datediff(mi,0,DB.[log_date]),0)
WHEN 'Hour' THEN dateadd(hh,datediff(hh,0,DB.[log_date]),0)
WHEN 'Day' THEN dateadd(dd,datediff(dd,0,DB.[log_date]),0)
WHEN 'Week' THEN dateadd(wk,datediff(wk,0,DB.[log_date]),0)
WHEN 'Month' THEN dateadd(mm,datediff(mm,0,DB.[log_date]),0)
WHEN 'Year' THEN dateadd(yy,datediff(yy,0,DB.[log_date]),0)
ELSE DB.[log_date] END ;
The parameters i'm passing are:
'Week'
'2016-05-16'
'2016-05-22'
6044
6044
'Week'
Note: This query runs without error in SQL Management Studio.
As requested here is a reworked version of your code using a sub-query before grouping. Since I don't have your database I can't guarantee that I have everything exactly right but give this a try.
I recommend always using a sub-query when your group by has complicated logic that will be repeated in the select. Some people would probably drop the second criteria and just say whenever the group by has complicated logic.
SELECT sub.Site_Code, sub.[Site], sub.[Utility], sub.[Meter Type],
sub.[log_date],
SUM(sub.[value]) as [value],
SUM(sub.[Cost]) as [cost],
SUM(sub.[CO]) as [CO],
sub.[Meter Name], sub.[Units], sub.[Meter_ID],
sub.[Parent], sub.[Meter_Description]
FROM (
SELECT EP.Site_Code AS [Site_Code], DB.[Site] AS [Site], DB.[Utility] AS [Utility],
CASE ? WHEN 'Raw' THEN dateadd(mi,datediff(mi,0,DB.[log_date]),0)
WHEN 'Hour' THEN dateadd(hh,datediff(hh,0,DB.[log_date]),0)
WHEN 'Day' THEN dateadd(dd,datediff(dd,0,DB.[log_date]),0)
WHEN 'Week' THEN dateadd(wk,datediff(wk,0,DB.[log_date]),0)
WHEN 'Month' THEN dateadd(mm,datediff(mm,0,DB.[log_date]),0)
WHEN 'Year' THEN dateadd(yy,datediff(yy,0,DB.[log_date]),0)
ELSE DB.[log_date]
END AS [log_date],
CASE WHEN DB.[value] >= 0 THEN DB.[value] ELSE 0 END AS [value],
CASE WHEN DB.[Cost] >=0 THEN DB.[cost] ELSE 0 END AS [Cost],
CASE WHEN DB.[CO2] >=0 THEN DB.[CO2] ELSE 0 END AS [CO],
MT.[Meter_type_name] AS [Meter Type],
MN.[Meter_Name] AS [Meter Name],
U.[Unit_Name] AS [Units],
EP.EnergyPoint_ID AS [Meter_ID],
EP.Parent_ID AS [Parent],
EP.Meter_Description AS [Meter_Description]
FROM [dbo].[JOHN_Dashboard] DB
INNER JOIN [dbo].[EnergyPoints] EP ON DB.[EnergyPoint_ID] = EP.[EnergyPoint_ID]
INNER JOIN [dbo].[Meter_Types] MT ON MT.[Meter_Type_ID] = EP.[Meter_Type_ID]
INNER JOIN [dbo].[Meter_Names] MN ON MN.[Meter_Name_ID] = EP.[Meter_Name_ID]
INNER JOIN [dbo].[Units] U ON U.[Unit_ID] = EP.[Unit_id]
WHERE [log_date] >= ? AND [Log_Date] < DATEADD(DAY, 1, ?)
AND ( ? IS NULL OR EP.Energypoint_ID = ?)
) sub
GROUP BY sub.Site_Code, sub.[Site], sub.[Utility], sub.[Meter Type],
sub.[Meter Name], sub.[Units], sub.[Meter_ID],
sub.[Parent], sub.[Meter_Description], sub.[log_date];