End as keyword in Oracle SQL Case statement - sql

I use two cases in below query to get results of daction & ApprovalType.
While running the below query in Oracle SQL creates two new temp columns as daction_1 & ApprovalType _1 for daction & ApprovalType columns respectively. Now, i want to use these keywords in my IDOC code but since temp columns are created I'm not able to use them. How to resolve this?
SELECT WH.dActionDate,
WH.xWF_SendTo,
WH.dAction,
ATY.ApprovalType,
WH.xWorkflowComments,
CASE
WHEN NVL(ApprovalType,'') IS NULL
THEN xPurposeForRejection
ELSE ApprovalType
END AS ApprovalType,
CASE
WHEN NVL(dAction,'') ='SendTo'
AND NVL(ApprovalType,'') IS NOT NULL
OR NVL(dAction,'') ='Approve'
THEN 'Approve'
ELSE 'Reject'
END AS dAction
FROM WorkflowHistory WH,
Reason Re,
ApprovalType ATY
WHERE UPPER(dDocName) = UPPER('D_1239178')
AND xPurposeForSubmission = Re.ReasonID(+)
AND xDocApproval = ATY.ApprovalTypeID(+)
AND (dAction IN('Reject','Approve')
OR (dAction ='SendTo'
AND ApprovalType IS NOT NULL))
AND ROWNUM <= 5
ORDER BY dActionDate DESC,
dActionMillis

Looking at column names I assume that Idoc is script language used in Oracle Webcenter Content Server (formerly Oracle UCM). I don't have a running instance on-hand to check, but I am pretty sure that you can create database view with columns you need and then see it as regular table in Configuration Manager. Following link provides some details of configuration process. The other option is to move your logic to Idoc code itself although it may be less performant.

Related

Dreaded "Missing Right Parenthesis" Error in Oracle SQL

We access an Oracle database through a web application. The web application is published, hosted and administered off-site. One component of the web application are dashboards, which use SQL to return data from the system on regular intervals that are then displayed and can trigger alarms should certain thresholds be reached.
The SQL has several parameters that are assigned in the dashboard setup: LOCATION, OWNER_DEPT, USING_DEPT and DAYS_AHEAD and appear to be working properly. Here is the query:
SELECT * FROM
(
SELECT DISTINCT
"MFIVE"."VIEW_WORK_REQ_OCC"."UNIT_NO" AS "UNIT NO", "MFIVE"."VIEW_WORK_REQ_OCC"."WORK_REQ_NO" AS "WORK REQ NO", "MFIVE"."VIEW_WORK_REQ_OCC"."JOB" AS "JOB",
CASE WHEN "MFIVE"."VIEW_WORK_REQ_OCC"."DUE_DATE" IS NULL THEN NULL ELSE ("MFIVE"."VIEW_WORK_REQ_OCC"."DUE_DATE") END AS "DUE DATE",
CASE WHEN "MFIVE"."VIEW_WORK_REQ_OCC"."FIRST_DATE" IS NULL THEN NULL ELSE ("MFIVE"."VIEW_WORK_REQ_OCC"."FIRST_DATE") END AS "FIRST DATE",
CASE WHEN "MFIVE"."VIEW_WORK_REQ_OCC"."LAST_DATE" IS NULL THEN NULL ELSE ("MFIVE"."VIEW_WORK_REQ_OCC"."LAST_DATE") END AS "LAST DATE"
FROM "MFIVE"."VIEW_WORK_REQ_OCC"
WHERE
("MFIVE"."VIEW_WORK_REQ_OCC"."MNT_PREVENTIVE_FL" = 'Y') AND
(UPPER("MFIVE"."VIEW_WORK_REQ_OCC"."LOCATION") LIKE UPPER(CONCAT(CONCAT('%', ':<LOCATION>'), '%'))) AND
(UPPER("MFIVE"."VIEW_WORK_REQ_OCC"."OWNER_DEPT") LIKE UPPER(CONCAT(CONCAT('%', ':<OWNER_DEPT>'), '%'))) AND
(UPPER("MFIVE"."VIEW_WORK_REQ_OCC"."USING_DEPT") LIKE UPPER(CONCAT(CONCAT('%', ':<USING_DEPT>'), '%'))) AND
("MFIVE"."VIEW_WORK_REQ_OCC"."DUE_DATE" >= SYSDATE + ':<DAYS_AHEAD>')
ORDER BY
"MFIVE"."VIEW_WORK_REQ_OCC"."UNIT_NO" ASC,
"MFIVE"."VIEW_WORK_REQ_OCC"."JOB" ASC,
CASE WHEN "MFIVE"."VIEW_WORK_REQ_OCC"."DUE_DATE" IS NULL THEN NULL ELSE ("MFIVE"."VIEW_WORK_REQ_OCC"."DUE_DATE") END AS "DUE DATE" ASC
)
The issue is with the statements involving "MFIVE"."VIEW_WORK_REQ_OCC"."DUE_DATE". We're attempting to return only values where DUE_DATE is greater than the SYSDATE plus the value in the DAYS_AHEAD parameter. Deleting these lines allows the query to execute properly; leaving them as-is returns the error ORA-00907: missing right parenthesis.
The majority of the SQL was lifted from the SQL as generated by an ad-hoc reporting component of the web application. The report runs properly, but we are not able to pass parameters through the ad-hoc reporting module. The modifications to the original were to add the bind variables.
I'm hoping someone can point me in the correct direction to remedy this issue. Any assistance is appreciated.
Thanks to Kaushik Nayak for helping me see the forest for the trees.
The correction only affects the ORDER BY clause:
...
ORDER BY
"MFIVE"."VIEW_WORK_REQ_OCC"."UNIT_NO" ASC,
"MFIVE"."VIEW_WORK_REQ_OCC"."JOB" ASC,
)

Syntax error on WITH clause

I am working on a web app and there are some long winded stored procedures and just trying to figure something out, I have extracted this part of the stored proc, but cant get it to work. The guy who did this is creating alias after alias.. and I just want to get a section to work it out. Its complaining about the ending but all the curly brackets seem to match. Thanks in advance..
FInputs is another stored procedure.. the whole thing is referred to as BASE.. the result of this was being put in a temp table where its all referred to as U. I am trying to break it down into separate sections.
;WITH Base AS
(
SELECT
*
FROM F_Inputs(1,1,100021)
),
U AS
(
SELECT
ISNULL(q.CoverPK,r.CoverPK) AS CoverPK,
OneLine,
InputPK,
ISNULL(q.InputName,r.InputName) AS InputName,
InputOrdinal,
InputType,
ParentPK,
InputTriggerFK,
ISNULL(q.InputString,r.InputString) AS InputString,
PageNo,
r.RatePK,
RateName,
Rate,
Threshold,
ISNULL(q.Excess,r.Excess) AS Excess,
RateLabel,
RateTip,
Refer,
DivBy,
RateOrdinal,
RateBW,
ngRequired,
ISNULL(q.RateValue,r.RateValue) AS RateValue,
ngClass,
ngPattern,
UnitType,
TableChildren,
TableFirstColumn,
parentRatePK,
listRatePK,
NewParentBW,
NewChildBW,
ISNULL(q.SumInsured,0) AS SumInsured,
ISNULL(q.NoItems,0) AS NoItems,
DisplayBW,
ReturnBW,
StringBW,
r.lblSumInsured,
lblNumber,
SubRateHeading,
TrigSubHeadings,
ISNULL(q.RateTypeFK,r.RateTypeFK) AS RateTypeFK,
0 AS ListNo,
0 AS ListOrdinal,
InputSelectedPK,
InputVis,
CASE
WHEN ISNULL(NewChildBW,0) = 0
THEN 1
WHEN q.RatePK is NOT null
THEN 1
ELSE RateVis
END AS RateVis,
RateStatus,
DiscountFirstRate,
DiscountSubsequentRate,
CoverCalcFK,
TradeFilter,
ngDisabled,
RateGroup,
SectionNo
FROM BASE R
LEFT JOIN QuoteInputs Q
ON q.RatePK = r.RatePK
AND q.ListNo = 0
AND q.QuoteId = 100021 )
Well, I explained the issue in the comments section already. I'm doing it here again, so future readers find the answer more easily.
A WITH clause is part of a query. It creates a view on-the-fly, e.g.:
with toys as (select * from products where type = 'toys') select * from toys;
Without the query at the end, the statement is invalid (and would not make much sense anyhow; if one wanted a permanent view for later use, one would use CREATE VIEW instead).

Handle null values within SQL IN clause

I have following sql query in my hbm file. The SCHEMA, A and B are schema and two tables.
select
*
from SCHEMA.A os
inner join SCHEMA.B o
on o.ORGANIZATION_ID = os.ORGANIZATION_ID
where
case
when (:pass = 'N' and os.ORG_ID in (:orgIdList)) then 1
when (:pass = 'Y') then 1
end = 1
and (os.ORG_SYNONYM like :orgSynonym or :orgSynonym is null)
This is a pretty simple query. I had to use the case - when to handle the null value of "orgIdList" parameter(when null is passed to sql IN it gives error). Below is the relevant java code which sets the parameter.
if (_orgSynonym.getOrgIdList().isEmpty()) {
query.setString("orgIdList", "pass");
query.setString("pass", "Y");
} else {
query.setString("pass", "N");
query.setParameterList("orgIdList", _orgSynonym.getOrgIdList());
}
This works and give me the expected output. But I would like to know if there is a better way to handle this situation(orgIdList sometimes become null).
There must be at least one element in the comma separated list that defines the set of values for the IN expression.
In other words, regardless of Hibernate's ability to parse the query and to pass an IN(), regardless of the support of this syntax by particular databases (PosgreSQL doesn't according to the Jira issue), Best practice is use a dynamic query here if you want your code to be portable (and I usually prefer to use the Criteria API for dynamic queries).
If not need some other work around like what you have done.
or wrap the list from custom list et.

How to Write a Where Clause to Handle Either a Specific Value or Any Value

I have a report with a table in Rails where users can optionally set filters like selecting a location or picking a range of dates and update the table via an ajax request.
Can I write this where clause so that it any date/blanks or all locations?
#orders = Order.where('created_at <= ? AND ? <= created_at AND location_id = ?', date_order_start, date_order_end, loc_filter)
The query above fails on blanks (e.g., "") and if I put nils they translate to nulls in the SQL.
To solve this problem right now I have a bunch of conditional statements that check whether value is present in the ajax request and then creates a different where clause depending on the case. My current conditionals are unwieldy, error prone and not scalable.
Searches on things like "wildcard sql" end up leading me to text searches (i.e., %) which I don't think fits in this case.
I am running on Rails 3.2 with postgresql.
I sometimes use an array of query statements and arguments like this:
queries = []
args = []
if some_condition
queries.push("created_at <= ?")
args.push(whatever_date)
end
if another_condition
queries.push("created_at >= ?")
args.push(another_date)
end
#order = Order.where(queries.join(" AND "), *args)

How to select if a row exists in HQL

EDIT: Specifically talking about querying against no table. Yes I can use exists, but I'd have to do
select case when exists (blah) then 1 else 0 end as conditionTrue
from ARealTableReturningMultipleRows
In T-SQL I can do:
select case when exists(blah) then 1 else 0 end as conditionTrue
In Oracle I can do:
select case when exists(blah) then 1 else 0 end as conditionTrue from DUAL
How can I achieve the same thing in HQL?
select count() seems like the second-best alternative, but I don't want to have to process every row in the table if I don't need to.
Short answer: I believe it's NOT possible.
My reasoning:
According to Where can I find a list of all HQL keywords? Hibernate project doesn't publish HQL grammar on their website, it's available in the Hibernate full distribution as a .g ANTLR file though.
I don't have much experience with .g files from ANTLR, but you can find this in the file (hibernate-distribution-3.6.1.Final/project/core/src/main/antlr/hql.g):
selectFrom!
: (s:selectClause)? (f:fromClause)? {
// If there was no FROM clause and this is a filter query, create a from clause. Otherwise, throw
// an exception because non-filter queries must have a FROM clause.
if (#f == null) {
if (filter) {
#f = #([FROM,"{filter-implied FROM}"]);
}
else
throw new SemanticException("FROM expected (non-filter queries must contain a FROM clause)");
}
which clearly states there are some HQL queries having no FROM clause, but that's acceptable if that's a filter query. Now again, I am not an expert in HQL/Hibernate, but I believe a filter query is not a full query but something you define using session.createFilter (see How do I turn item ordering HQL into a filter query?), so that makes me think there's no way to omit the FROM clause.
I'm use fake table with one row for example MyDual.
select case when exists(blah) then 1 else 0 end as conditionTrue from MyDual
According to http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-expressions it looks like they support both case and exists statements.