SQL in clause max items
Could you tell me the maximum allowed numbers of items in the "IN" clause of a SQL query under Oracle 10, Oracle 9, and Oracle 8?
Thanks,
john
Tested in 9i and 10g:
michaels> DECLARE
str LONG;
BEGIN
FOR i IN 1 .. 1100
LOOP
str := str || i || ',';
END LOOP;
EXECUTE IMMEDIATE 'select * from dual where dummy in (' || RTRIM (str, ',')
|| ')';
END;
Error at line 1
ORA-01795: maximum number of expressions in a list is 1000
ORA-06512: at line 9
Similar Messages
-
Not to able add sql query in the item source
Hi,
I am getting this error when i am trying to add the sql query in the item source
ORA-20505: Error in DML: p_rowid=3206911131098131, p_alt_rowid=ID, p_rowid2=, p_alt_rowid2=. ORA-01461: can bind a LONG value only for insert into a LONG column
SELECT
"UCL"
FROM
SELECT
TRUNC((
(SUM("EV FINAL" / 100) / COUNT("Object_Name") )
+
3 *
SQRT
(SUM("EV FINAL" / 100) * SUM("EV FINAL" / 100) ) / COUNT("Object_Name") -
(SUM("EV FINAL" / 100) / COUNT("Object_Name")) * (SUM("EV FINAL" / 100) / COUNT("Object_Name"))
),3) "UCL"
FROM
SELECT
Pro.Project_Name "Project Name",
POBJ.NAME "Object_Name",
TRUNC((
( ( NVL(AEV."Total Actual",0) - (NVL( (NVL( (MAX(X."Incoming-Doc") / 100),0) * NVL(ID."INCOMMING_DOC",0) ) ,0 ) +
NVL( (NVL( (MAX(X."Design") / 100),0) * NVL(D."DESIGN",0) ), 0 ) +
NVL( (NVL( (MAX(X."Build") / 100) ,0) * NVL(B."BUILD",0) ),0 ) +
NVL( (NVL( (MAX(X."Testing") / 100),0) * NVL(T."TESTING",0) ),0 ) +
NVL( (NVL( (MAX(X."Release") / 100),0) * NVL(R."RELEASE",0) ),0 ) ) )
DECODE(
(NVL( (NVL( (MAX(X."Incoming-Doc") / 100),0) * NVL(ID."INCOMMING_DOC",0) ) ,0 ) +
NVL( (NVL( (MAX(X."Design") / 100),0) * NVL(D."DESIGN",0) ), 0 ) +
NVL( (NVL( (MAX(X."Build") / 100) ,0) * NVL(B."BUILD",0) ),0 ) +
NVL( (NVL( (MAX(X."Testing") / 100),0) * NVL(T."TESTING",0) ),0 ) +
NVL( (NVL( (MAX(X."Release") / 100),0) * NVL(R."RELEASE",0) ),0 ) ),0,NULL,
(NVL( (NVL( (MAX(X."Incoming-Doc") / 100),0) * NVL(ID."INCOMMING_DOC",0) ) ,0 ) +
NVL( (NVL( (MAX(X."Design") / 100),0) * NVL(D."DESIGN",0) ), 0 ) +
NVL( (NVL( (MAX(X."Build") / 100) ,0) * NVL(B."BUILD",0) ),0 ) +
NVL( (NVL( (MAX(X."Testing") / 100),0) * NVL(T."TESTING",0) ),0 ) +
NVL( (NVL( (MAX(X."Release") / 100),0) * NVL(R."RELEASE",0) ),0 ) ) ) ) * 100),2)
|| '%' "EV_INITIAL",
TRUNC((
( (NVL(AEV."Total Actual",0) - ( NVL( (NVL( (MAX(X."Incoming-Doc") / 100),0) * NVL(IDR."INCOMMING_DOC_REPLAN",0) ),0) +
NVL( (NVL( (MAX(X."Design") / 100),0) * NVL(DR."DESIGN_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Build")/100),0) * NVL(BR."BUILD_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Testing") / 100),0) * NVL(TR."TESTING_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Release")/100),0) * NVL(RR."RELEASE_REPLAN",0)),0) ) )
DECODE(
( NVL( (NVL( (MAX(X."Incoming-Doc") / 100),0) * NVL(IDR."INCOMMING_DOC_REPLAN",0) ),0) +
NVL( (NVL( (MAX(X."Design") / 100),0) * NVL(DR."DESIGN_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Build")/100),0) * NVL(BR."BUILD_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Testing") / 100),0) * NVL(TR."TESTING_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Release")/100),0) * NVL(RR."RELEASE_REPLAN",0)),0) ) ,0,NULL,
( NVL( (NVL( (MAX(X."Incoming-Doc") / 100),0) * NVL(IDR."INCOMMING_DOC_REPLAN",0) ),0) +
NVL( (NVL( (MAX(X."Design") / 100),0) * NVL(DR."DESIGN_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Build")/100),0) * NVL(BR."BUILD_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Testing") / 100),0) * NVL(TR."TESTING_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Release")/100),0) * NVL(RR."RELEASE_REPLAN",0)),0) ) ) ) * 100),2) "EV FINAL",
TRUNC(BRV."RSV",2) "Revised SV"
FROM
PROJECTS PRO,
PROJECT_OBJECTS POBJ,
INITIAL_EFFORT IE,
SCHEDULE_VARIANCES SV,
INITIAL_EFFORT_VIEW IEV,
INCOMMING_DOC ID,
DESIGN D,
BUILD B,
TESTING T,
RELEASE R,
INCOMMING_DOC_REPLAN IDR,
DESIGN_REPLAN DR,
BUILD_REPLAN BR,
TESTING_REPLAN TR,
RELEASE_REPLAN RR,
ACTUAL_EFFORT_VIEW AEV,
REPLAN_INITIAL_EFFORT_VIEW RIEV,
BSV_RSV_VIEW BRV,
SELECT
distinct
pro.project_name "Project Name",
pobj.name "Object Name",
PRO.ID "PRO_ID",
POBJ.ID "POBJ_ID",
CASE
WHEN
ts.status in ('CLOSE','CLOSED','Closed') AND
tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review') THEN
TO_CHAR('100')
WHEN
upper(ts.status) like upper('ACCEPTED') AND
tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review') THEN
TO_CHAR('75')
WHEN
ts.status IN ('RIP','WIP','REJECTED','Rejected') AND
tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review') THEN
TO_CHAR('50')
WHEN
POBJ.ID IN (SELECT POBJ.ID FROM projects pro,project_objects pobj,task tsk,skip_phase sp,employees
emp,employee_project_pairs epp
WHERE pobj.pro_id = pro.id and epp.pro_id = pro.id AND sp.tas_id = tsk.id and
pobj.id = sp.OBJ_ID and pro.id = sp.pro_id
and tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review')
AND PRO.ID = :p2_projects ) THEN
TO_CHAR('100')
END "Incoming-Doc",
CASE
WHEN
ts.status in ('CLOSE','CLOSED','Closed') AND
tsk.name in ('Design Review','Design - Review','TDD - Review') THEN
TO_CHAR('100')
WHEN
UPPER(ts.status) LIKE UPPER('ACCEPTED') AND
tsk.name in ('Design Review','Design - Review','TDD - Review') THEN
TO_CHAR('75')
WHEN
ts.status IN ('RIP','WIP','REJECTED','Rejected') AND
tsk.name in ('Design Review','Design - Review','TDD - Review')
THEN
TO_CHAR('50')
WHEN
POBJ.ID IN (SELECT POBJ.ID FROM projects pro,project_objects pobj,task tsk,skip_phase sp,employees
emp,employee_project_pairs epp
WHERE pobj.pro_id = pro.id and epp.pro_id = pro.id AND sp.tas_id = tsk.id and
pobj.id = sp.OBJ_ID and pro.id = sp.pro_id
and tsk.name in ('Design Review','Design - Review','TDD - Review')
AND PRO.ID = :p2_projects ) THEN
TO_CHAR('100')
END "Design",
CASE
WHEN
ts.status in ('CLOSE','CLOSED','Closed') AND
tsk.name in ('Build Review','Build - Review','Code - Review','Code') THEN
TO_CHAR('100')
WHEN
UPPER(ts.status) LIKE UPPER('ACCEPTED') AND
tsk.name in ('Build Review','Build - Review','Code - Review','Code') THEN
TO_CHAR('75')
WHEN
ts.status IN ('RIP','WIP','REJECTED','Rejected') AND
tsk.name in ('Build Review','Build - Review','Code - Review','Code') THEN
TO_CHAR('50')
WHEN
POBJ.ID IN (SELECT POBJ.ID FROM projects pro,project_objects pobj,task tsk,skip_phase sp,employees
emp,employee_project_pairs epp
WHERE pobj.pro_id = pro.id and epp.pro_id = pro.id AND sp.tas_id = tsk.id and
pobj.id = sp.OBJ_ID and pro.id = sp.pro_id
and tsk.name in ('Build Review','Build - Review','Code - Review','Code')
AND PRO.ID = :p2_projects ) THEN
TO_CHAR('100')
END "Build",
CASE
WHEN
ts.status in ('CLOSE','CLOSED','Closed') AND
tsk.name in ('Test Result Review','Test Result - Review','UTR - Review') THEN
TO_CHAR('100')
WHEN
UPPER(ts.status) LIKE UPPER('ACCEPTED') AND
tsk.name in ('Test Result Review','Test Result - Review','UTR - Review') THEN
TO_CHAR('75')
WHEN
ts.status IN ('RIP','WIP','REJECTED','Rejected') AND
tsk.name in ('Test Result Review','Test Result - Review','UTR - Review') THEN
TO_CHAR('50')
WHEN
POBJ.ID IN (SELECT POBJ.ID FROM projects pro,project_objects pobj,task tsk,skip_phase sp,employees
emp,employee_project_pairs epp
WHERE pobj.pro_id = pro.id and epp.pro_id = pro.id AND sp.tas_id = tsk.id and
pobj.id = sp.OBJ_ID and pro.id = sp.pro_id
and tsk.name in ('Test Result Review','Test Result - Review','UTR - Review')
AND PRO.ID = :p2_projects ) THEN
TO_CHAR('100')
END "Testing",
CASE
WHEN
ts.status in ('CLOSE','CLOSED','Closed') AND
tsk.name in ('Release-Review','Release - Verification',
'Migration & Release - Review') THEN
TO_CHAR('100')
WHEN
UPPER(ts.status) LIKE UPPER('ACCEPTED') AND
tsk.name in ('Release-Review','Release - Verification',
'Migration & Release - Review') THEN
TO_CHAR('75')
WHEN
ts.status IN ('RIP','WIP','REJECTED','Rejected') AND
tsk.name in ('Release-Review','Release - Verification','Migration & Release - Review') THEN
TO_CHAR('50')
WHEN
POBJ.ID IN (SELECT POBJ.ID FROM projects pro,project_objects pobj,task tsk,skip_phase sp,employees
emp,employee_project_pairs epp
WHERE pobj.pro_id = pro.id and epp.pro_id = pro.id AND sp.tas_id = tsk.id and
pobj.id = sp.OBJ_ID and pro.id = sp.pro_id
and tsk.name in ('Release-Review','Release - Verification','Migration & Release - Review' )
AND PRO.ID = :p2_projects ) THEN
TO_CHAR('100')
END "Release"
FROM
task_status ts,projects pro,project_objects pobj,task tsk
,employees emp,employee_project_pairs epp,REVIEW_ITEMS RI
WHERE
pobj.pro_id = pro.id
and pro.id = ts.pro_id
and pobj.id = ts.pro_obj_id
and tsk.id = ts.task_id
and emp.id = epp.emp_id
and epp.pro_id = pro.id
and ts.id = ri.ts_id
AND PRO.ID = :p2_projects
and tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review','Design Review','Design - Review','TDD - Review',
'Build Review','Build - Review','Code - Review','Code',
'Test Result Review','Test Result - Review','UTR - Review',
'Release-Review','Release - Verification','Migration & Release - Review')
and ri.open_timestamp in
SELECT
distinct
max(ri.open_timestamp)
FROM
task_status ts,projects pro,project_objects pobj,task tsk
,employees emp,employee_project_pairs epp,REVIEW_ITEMS RI
WHERE
pobj.pro_id = pro.id
and pro.id = ts.pro_id
and pobj.id = ts.pro_obj_id
and tsk.id = ts.task_id
and emp.id = epp.emp_id
and epp.pro_id = pro.id
and ts.id = ri.ts_id
and tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review','Design Review','Design - Review','TDD - Review',
'Build Review','Build - Review','Code - Review','Code',
'Test Result Review','Test Result - Review','UTR - Review',
'Release-Review','Release - Verification','Migration & Release - Review')
AND PRO.ID = :p2_projects
GROUP BY POBJ.NAME,TSK.NAME )
UNION
select
distinct
pro.project_name "Project Name",
pobj.name "Object Name",
PRO.ID "PRO_ID",
POBJ.ID "POBJ_ID",
case
when
tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review') THEN
TO_CHAR('100')
end "Incoming-Doc",
case
when
tsk.name in ('Design Review','Design - Review','TDD - Review') THEN
TO_CHAR('100')
end "Design",
case
when
tsk.name in ('Build Review','Build - Review','Code - Review','Code') THEN
TO_CHAR('100')
end "Build",
case
when
tsk.name in ('Test Result Review','Test Result - Review','UTR - Review') THEN
TO_CHAR('100')
end "Testing",
case
when
tsk.name in ('Release-Review','Release - Verification',
'Migration & Release - Review') THEN
TO_CHAR('100')
end "Release"
FROM
projects pro
,project_objects pobj
,task tsk
,skip_phase sp
,employees emp
,employee_project_pairs epp
WHERE
pobj.pro_id = pro.id
and epp.pro_id = pro.id
AND sp.tas_id = tsk.id
and pobj.id = sp.OBJ_ID
and pro.id = sp.pro_id
and tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review','Design Review','Design - Review',
'TDD - Review','Build Review','Build - Review','Code - Review','Code',
'Test Result Review','Test Result - Review','UTR - Review',
'Release-Review','Release - Verification','Migration & Release - Review')
and pro.id = :p2_projects ) X
WHERE
PRO.ID = POBJ.PRO_ID AND
PRO.ID = IE.PROJECT_NAME AND
UPPER(POBJ.NAME) = UPPER(IE.OBJECT_NAME) AND
PRO.ID = SV.PROJECT_NAME AND
UPPER(POBJ.NAME) = UPPER(SV.OBJECT_NAME) AND
PRO.ID = :p2_projects
AND PRO.ID = X."PRO_ID"
AND POBJ.ID = X."POBJ_ID"(+)
AND PRO.ID = IEV."PRO_ID"
AND POBJ.ID = IEV."POBJ_ID"
AND PRO.ID = ID."PRO_ID"
AND POBJ.ID = ID."POBJ_ID"
AND PRO.ID = D."PRO_ID"
AND POBJ.ID = D."POBJ_ID"
AND PRO.ID = B."PRO_ID"
AND POBJ.ID = B."POBJ_ID"
AND PRO.ID = T."PRO_ID"
AND POBJ.ID = T."POBJ_ID"
AND PRO.ID = R."PRO_ID"
AND POBJ.ID = R."POBJ_ID"
AND PRO.ID = IDR."PRO_ID"
AND POBJ.ID = IDR."POBJ_ID"
AND PRO.ID = DR."PRO_ID"
AND POBJ.ID = DR."POBJ_ID"
AND PRO.ID = BR."PRO_ID"
AND POBJ.ID = BR."POBJ_ID"
AND PRO.ID = TR."PRO_ID"
AND POBJ.ID = TR."POBJ_ID"
AND PRO.ID = RR."PRO_ID"
AND POBJ.ID = RR."POBJ_ID"
AND PRO.ID = AEV."PRO_ID"
AND POBJ.ID = AEV."POBJ_ID"
AND PRO.ID = RIEV."PRO_ID"
AND POBJ.ID = RIEV."POBJ_ID"
AND PRO.ID = BRV."PRO_ID"
AND POBJ.ID = BRV."POBJ_ID"
group by
PRO.PROJECT_NAME,
POBJ.NAME,
SV.status,
sv.comments,
ID."INCOMMING_DOC",D."DESIGN",B."BUILD",T."TESTING",R."RELEASE",
IDR."INCOMMING_DOC_REPLAN",DR."DESIGN_REPLAN",BR."BUILD_REPLAN",TR."TESTING_REPLAN",RR."RELEASE_REPLAN",
AEV."Total Actual",IEV."Total Plan",RIEV."Total Plan",
BRV."BSV",BRV."RSV",POBJ.Complexity,POBJ.PROGRAM_TYPE,pro.id,pobj.id,BRV."Status"
wht is the mistake i am doing here please suggets
thanks
SudhirCan you just setup an Excel/Essbase retrieval to get the data you need? You can't use SQL to query Essbase; here is a blog post that talks about it:
http://timtows-hyperion-blog.blogspot.com/2008/01/why-you-cant-use-sql-to-query-essbase.html
Since I made that post, I have found out that Essbase has now been integrated into the latest version of the Oracle BI Server and, technically, you could use SQL to query the data in Essbase via the Oracle BI Server if you have the right version.
Tim Tow
Applied OLAP, Inc -
I have the privilege of performing a very tedious task.
We have some home grown regular expressions in our company. I now need to expand these regular expressions.
Samples:
a = 0-3
b = Null, 0, 1
Expression: Meaning
1:5: 1,2,3,4,5
1a: 10, 11, 12, 13
1b: 1, 10, 11
1[2,3]ab: 120, 1200, 1201, ....
It get's even more inetersting because there is a possibility of 1[2,3]a.ab
I have created two base queries to aid me in my quest. I am using the SQL MODEL clause to solve this problem. I pretty confident that I should be able to convert evrything into a range and the use one of the MODEL clause listed below.
My only confusion is how do I INCREMENT dynamically. The INCREMENT seems to be a constant in both a FOR and ITERATE statement. I need to figure a way to increment with .01, .1, etc.
Any help will be greatly appreciated.
CODE:
Reference: http://www.sqlsnippets.com/en/topic-11663.html
Objective: Expand a range with ITERATE
WITH t AS
(SELECT '2:4' pt
FROM DUAL
UNION ALL
SELECT '6:9' pt
FROM DUAL)
SELECT pt AS code_expression
-- , KEY
-- , min_key
-- , max_key
, m_1 AS code
FROM t
MODEL
PARTITION BY (pt)
DIMENSION BY ( 0 AS KEY )
MEASURES (
0 AS m_1,
TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key,
TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key
RULES
-- UPSERT
ITERATE (100000) UNTIL ( ITERATION_NUMBER = max_key[0] - min_key[0] )
m_1[ITERATION_NUMBER] = min_key[0] + ITERATION_NUMBER
ORDER BY pt, m_1
Explanation:
Line numbers are based on the assupmtion that "WITH t AS" starts at line 5.
If you need detailed information regarding the MODEL clause please refer to
the Refrence site stated above or read some documentation.
Partition-
Line 18: PARTITION BY (pt)
This will make sure that each "KEY" will start at 0 for each value of pt.
Dimension-
Line 19: DIMENSION BY ( 0 AS KEY )
This is necessary for the refrences max_key[0], and min_key[0] to work.
Measures-
Line 21: 0 AS m_1
A space holder for new values.
Line 22: TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key
The result is '1' for '1:5'.
Line 23: TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key
The result is '5' for '1:5'.
Rules-
Line 26: UPSERT
This makes it possible for new rows to be created.
Line 27: ITERATE (100000) UNTIL ( ITERATION_NUMBER = max_key[0] - min_key[0] )
This reads ITERATE 100000 times or UNTIL the ITERATION_NUMBER = max_key[0] - min_key[0]
which would be 4 for '1:5', but since the ITERATION_NUMBER starts at 0, whatever follows
is repaeted 5 times.
Line 29: m_1[ITERATION_NUMBER] = min_key[0] + ITERATION_NUMBER
m_1[ITERATION_NUMBER] means m_1[Value of Dimension KEY].
Thus for each row of KEY the m_1 is min_key[0] + ITERATION_NUMBER.
Reference: http://www.sqlsnippets.com/en/topic-11663.html
Objective: Expand a range using FOR
WITH t AS
(SELECT '2:4' pt
FROM DUAL
UNION ALL
SELECT '6:9' pt
FROM DUAL)
, base AS
SELECT pt AS code_expression
, KEY AS code
, min_key
, max_key
, my_increment
, m_1
FROM t
MODEL
PARTITION BY (pt)
DIMENSION BY ( CAST(0 AS NUMBER) AS KEY )
MEASURES (
CAST(NULL AS CHAR) AS m_1,
TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key,
TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key,
.1 AS my_increment
RULES
-- UPSERT
m_1[FOR KEY FROM min_key[0] TO max_key[0] INCREMENT 1] = 'Y'
ORDER BY pt, KEY, m_1
SELECT code_expression, code
FROM base
WHERE m_1 = 'Y'
Explanation:
Line numbers are based on the assupmtion that "WITH t AS" starts at line 5.
If you need detailed information regarding the MODEL clause please refer to
the Refrence site stated above or read some documentation.
Partition-
Line 21: PARTITION BY (pt)
This will make sure that each "KEY" will start at 0 for each value of pt.
Dimension-
Line 22: DIMENSION BY ( 0 AS KEY )
This is necessary for the refrences max_key[0], and min_key[0] to work.
Measures-
Line 24: CAST(NULL AS CHAR) AS m_1
A space holder for results.
Line 25: TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key
The result is '1' for '1:5'.
Line 26: TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key
The result is '5' for '1:5'.
Line 27: .1 AS my_increment
The INCREMENT I would like to use.
Rules-
Line 30: UPSERT
This makes it possible for new rows to be created.
However seems like it is not necessary.
Line 32: m_1[FOR KEY FROM min_key[0] TO max_key[0] INCREMENT 1] = 'Y'
Where the KE value is between min_key[0] and max_key[0] set the value of m_1 to 'Y'
*/Of course, you can accomplish the same thing without MODEL using an Integer Series Generator like this.
create table t ( min_val number, max_val number, increment_size number );
insert into t values ( 2, 3, 0.1 );
insert into t values ( 1.02, 1.08, 0.02 );
commit;
create table integer_table as
select rownum - 1 as n from all_objects where rownum <= 100 ;
select
min_val ,
increment_size ,
min_val + (increment_size * n) as val
from t, integer_table
where
n between 0 and ((max_val - min_val)/increment_size)
order by 3
MIN_VAL INCREMENT_SIZE VAL
1.02 .02 1.02
1.02 .02 1.04
1.02 .02 1.06
1.02 .02 1.08
2 .1 2
2 .1 2.1
2 .1 2.2
2 .1 2.3
2 .1 2.4
2 .1 2.5
2 .1 2.6
2 .1 2.7
2 .1 2.8
2 .1 2.9
2 .1 3
15 rows selected.--
Joe Fuda
http://www.sqlsnippets.com/ -
How can I set a variable number of values in a SQL IN clause?
Hi,
How can I set a variable number of values in a SQL IN clause without having to change the text of the SQL statement each time?
I read the link http://radio.weblogs.com/0118231/2003/06/18.html. as steve wrote.
SELECT *
FROM EMP
WHERE ENAME IN (?)
But we need the steps not to create type in the system and would there be any other solution if we would like to use variable number of values in a SQL IN clause ?
We are using JDeveloper 10.1.3.2 with Oracle Database 10.1.3.2
Thanks
RajHi,
can you please explain why the solution from steve is not the right solution for you.
regards
Peter -
Generate a SQL "IN" clause using ALDSP
Problem Summary
ALDSP: Generate a SQL "IN" clause
Problem Description
I would like to know if there is a possibility of generating an SQL "IN" clause using ALDSP.
I would need the XQuery construct to create an SQLsomething like-
select * from emp where dept_no in ('101', '201', '301');
The values for dept_no would be passed at runtime.
(Or)
Will be I able to create a physical data service using the SQL - select * from emp where dept_no in ?
If yes, how do I map the parameter to "?"
Thanks.Mike,
Thanks for the response. The section that you are taking about is to push joins to DB. Joining tables is not the problem that I am facing.
I will rephrase the problem.
I would like to know if there is a possibility of creating a ALDSP physical data service (.ds file) with the SQL as select * from employee where emp_id in ?
and I should be able to pass multiple employee ids to the "?" parameter. select * from emp where emp_id in ('101', '201', '301');
There is no fixed number of ids that a user can pass.
Thanks. -
SQL IN clause with a Tool variable
We are using using Forte 3.M.2 (just upgraded from 3.G, finally).
Platform is AIX 4.3. Database is DB2 (UDB) (version 5.2 i think).
True, I haven't tried my code on any other platform. I think it should work on NT, because one of our other teams members has set up an NT laptop for portable demos. And it has DB2 (NT version i guess) loaded on it.
Dynamic sql is not really that bad, if you have to go that route to build your list.
Let me know how it goes.
Steven Barnes
Daniel González de Lucas <danieleam.es> 07/28/00 04:06AM >>>We are getinng some trouble, the DB Manager seems to try to convert
:OfficeList to a unique integer lets say:
:OfficeList value is 3,4,7
so the IN clause
trying with Oracle 8.1.5 converts 3,4,7 in a unique integer (a extrange
value because doesn't match with 3,4 nor 7).
trying with SQL Server 6.5 gives an error converting 3,4,7 to a unique
tinyint.
The idea is that with your sintax the DB Manager must split the TextData
into 3 integer values. I think that it works fine in some DB Managers and
not in others.
Which release and vendor of DB Manager you use?
Which Forté release?
Thank you very much in advance.
Daniel.
----- Original Message -----
From: "Steve Barnes" <DHS9126dhs.state.il.us>
To: <danieleam.es>; <kamranaminyahoo.com>
Sent: Thursday, July 27, 2000 1:55 PM
Subject: Re: (forte-users) SQL IN clause with a Tool variable
I needed to have an "IN" clause for some numbers. Here's how I did it:
GetOffices():TextData method...
Offices : TextData = new ;
for (x : integer) in sql select MyIntegerColumn
from MY_TABLE
where whatever condition
on session MyDBSession do
Offices.Concat(x) ;
Offices.Concat(',') ;
end for ;
return (Offices.CopyRange(0,Offices.ActualSize -1)) ; // get rid of lastcomma
in actual sql.....
OfficeList : TextData ;
OfficeList = GetOffices() ;
sql select * from MyTable where MyField in (:OfficeList)
on session MyDBSession ;
Works very well.
Steven Barnes
Daniel González de Lucas <danieleam.es> 07/27/00 05:32AM >>>Hello,
To do a select we have two options:
select * from MyTable
where MyField in ('a','b','c')
we would like to do the same but using a forté variable in the IN clause.
select * from MyTable
where MyField in (:ToolVar)
What should we do and what kind of variable or array of variables shouldwe use in ToolVar to do the same than in first option?
>
Has anybody done this without a dynamic query?
Best regards
Daniel
For the archives, go to: http://lists.xpedior.com/forte-users and use
the login: forte and the password: archive. To unsubscribe, send in a new
email the word: 'Unsubscribe' to: forte-users-requestlists.xpedior.com -
SQL IN clause with Bind parameter?
Hi
I have a simple task that hasn't been so simple to figure out. I want to allow a user to search for one or more comma-separated values in a simple JClient ADF app. Is there a way to use a SQL IN clause with a single bind variable? e.g. SELECT TITLE FROM CITATION WHERE ID IN (:0)
When I pass a single value it works fine but a comma separated list doesn't.
Thanks
JohnUpdate: I wanted to combine the techniques found in two of Steve Muench's articles -
1) Providing Default Values for View Object Bind Variables (so I could display an ADF-bound JPanel with defaults)
http://radio.weblogs.com/0118231/stories/2004/10/07/providingDefaultValuesForViewObjectBindVariables.html
2) Array of String Domain Example (so a user could enter one or more comma-separated values into a text box for DB searches)
http://radio.weblogs.com/0118231/stories/2004/09/23/notYetDocumentedAdfSampleApplications.html
I learned some helpful stuff about the framework but spent lots of time banging my head against the wall because the two examples wouldn't work when directly combined. To best understand this, be sure to study Steve's examples above.
In example 1 Steve passes an array of objects (Object[] DEFAULT_VALUES) to the ViewObject's where clause using the setWhereClauseParams(Object[] values). However, in example 2 he creates an Oracle Array which contains an Oracle ArrayDescriptor, Connection, and array of values to pass to the "IN" bind variable. Also, example 1 allows for multiple bind vars to be included whereas example 2 allows for an array of data to be passed to a single bind var. Even though my code provides an array to a single bind var (per ex. 2) it should still allow for the passage of multiple bind vars with minimal code modification.
Code from Steve's example 1 was copied into my EmpView ViewObject but certain modifications were necessary:
1) Change the ViewObject's DEFAULT_VALUES from Object[] to String[].
2) Modify the executeQueryForCollection() method in the ViewObject to call a function which will set the bind variables as Oracle Arrays (effectively converting the "params" data type from that of String[] to Oracle Array[])
3) Create a setManagerID(String[]) method in the EmpView object and expose it to the client.
(there are a number of others so it's best for you to go through the code and compare)
I finally got it working so I'm attaching the code, however beware - I'm new to this so there may be other, better ways to go about it. Also, there are no framework bind vars so that section of code is never executed...it compiles but may fail at run time.
In order for this to work I suggest you use JDev to re-create the EmpView and Panel1 objects. This will ensure that the necessary ADF framework components are generated. Once complete, then copy in the code provided.
*File: EmpViewImpl.java
*Created as Read-Only access view object with the
*query:
*select manager_id, last_name from hr.employees
*where manager_id IN
*(select * from TABLE(CAST(:0 as TABLE_OF_VARCHAR)))
*order by manager_id
package model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import oracle.jbo.domain.Array;
import oracle.jbo.server.ViewObjectImpl;
import oracle.sql.ArrayDescriptor;
// --- File generated by Oracle ADF Business Components Design Time.
// --- Custom code may be added to this class.
// --- Warning: Do not modify method signatures of generated methods.
public class EmpViewImpl extends ViewObjectImpl implements model.common.EmpView
private ArrayDescriptor descriptor;
private final static String[] DEFAULT_VALUES_STRING = new String[]{"100"};
private final static int NUM_DEFAULT_VALUES = DEFAULT_VALUES_STRING.length;
* This is the default constructor (do not remove)
public EmpViewImpl()
protected void executeQueryForCollection (Object qc, Object[] params, int numUserParams)
Object pars[] = null;
// Bind default variables only if none have been provided by the user
if (numUserParams == 0)
numUserParams = NUM_DEFAULT_VALUES;
int numFwkSuppliedBindVals = (params != null) ? params.length : 0;
if (numFwkSuppliedBindVals > 0)
// Allocate a new Object[] array with enough room for both user- and framework-supplied vars
Object[] newBinds = new Object[numFwkSuppliedBindVals + numUserParams];
// Copy the framework-supplied bind variables into a new Object[] array
// leaving enough slots at the beginning for the user-supplied vars
System.arraycopy(params, 0, newBinds, numUserParams, numFwkSuppliedBindVals);
// Now copy in the user-supplied vars to the beginning of the array
System.arraycopy(DEFAULT_VALUES_STRING, 0, newBinds, 0, numUserParams);
params = newBinds;
} else
params = DEFAULT_VALUES_STRING;
// We have to call this method to convert the default values into the proper Oracle Array expected by the query.
// If you set a debugger breakpoint at this line you can see that the "params" data type changes from String[] to Object[]
setWhereClauseParamsToDefaultValues();
// Now retrieve the params of the new data type
params = this.getWhereClauseParams();
super.executeQueryForCollection(qc, params, numUserParams);
private void setWhereClauseParamsToDefaultValues()
this.setManagerID(DEFAULT_VALUES_STRING);
private Connection getCurrentConnection() throws SQLException
// Create a bogus statement so that we can access our current connection
// JBD note - Does this get run each time??
PreparedStatement st = getDBTransaction().createPreparedStatement("commit", 1);
Connection conn = st.getConnection();
st.close();
return conn;
private synchronized void setupDescriptor(Connection conn) throws SQLException
descriptor = new ArrayDescriptor("TABLE_OF_VARCHAR", conn);
* setManagerID
* Exposed to client to accept an array of values (presumably passed in by user-entry into text box
* @param aryMan
public void setManagerID(String[] aryMan)
Array arr = null;
try
// Find the connection
Connection conn = getCurrentConnection();
//Create the ArrayDescriptor by looking for our custom data type in our connected DB
if(descriptor == null)
setupDescriptor(conn);
// Create the Oracle Array by passing in the descriptor, connection, and object array of data
arr = new Array(descriptor, conn, aryMan);
} catch (SQLException se)
System.out.println("SQL Exception: " + se.getMessage());
// Now we can set the WHERE clause parameter bind variable (index = 0) to the Oracle Array
if (arr != null) setWhereClauseParam(0, arr);
* FILE: Panel1.java
* Created as an empty panel. Then a JTextField, a
* JButton, and an EmpView1 table were dragged on.
* A custom actionPerformed method was created for the
* JButton which grabs the data from the text box.
* The user can enter either a single manager id or
* multiple, comma-separated ids.
* All code in this class was created by JDev except
* for the Jbutton action
package view;
import java.awt.*;
import javax.swing.*;
import model.common.*;
import oracle.jbo.ApplicationModule;
import oracle.jbo.SQLStmtException;
import oracle.jbo.uicli.jui.*;
import oracle.jbo.uicli.controls.*;
import oracle.jbo.uicli.binding.*;
import oracle.jdeveloper.layout.*;
import oracle.adf.model.*;
import oracle.adf.model.binding.*;
import java.util.ArrayList;
import oracle.jdeveloper.layout.VerticalFlowLayout;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Panel1 extends JPanel implements JUPanel
* NOTE: You need to have previous created the Oracle8 type named
* ==== TABLE_OF_VARCHAR by doing the following at the SQL*Plus
* command prompt:
* create type table_of_varchar as table of varchar2(20)
// Panel binding definition used by design time
private JUPanelBinding panelBinding = new JUPanelBinding("Panel1UIModel");
private VerticalFlowLayout verticalFlowLayout1 = new VerticalFlowLayout();
private JTextField jTextField1 = new JTextField();
private JButton jButton1 = new JButton();
private JTable jTable1 = new JTable();
* The default constructor for panel
public Panel1()
* the JbInit method
public void jbInit() throws Exception
this.setLayout(verticalFlowLayout1);
jTextField1.setText("jTextField1");
jButton1.setText("jButton1");
jButton1.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
jButton1_actionPerformed(e);
this.add(jTextField1, null);
this.add(jButton1, null);
this.add(jTable1, null);
jTable1.setModel((TableModel)panelBinding.bindUIControl("EmpView1", jTable1));
public static void main(String [] args)
try
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
catch(Exception exemp)
exemp.printStackTrace();
Panel1 panel = new Panel1();
panel.setBindingContext(JUTestFrame.startTestFrame("DataBindings.cpx", "null", panel, panel.getPanelBinding(), new Dimension(400, 300)));
panel.revalidate();
* JUPanel implementation
public JUPanelBinding getPanelBinding()
return panelBinding;
private void unRegisterProjectGlobalVariables(BindingContext bindCtx)
JUUtil.unRegisterNavigationBarInterface(panelBinding, bindCtx);
private void registerProjectGlobalVariables(BindingContext bindCtx)
JUUtil.registerNavigationBarInterface(panelBinding, bindCtx);
public void setBindingContext(BindingContext bindCtx)
if (panelBinding.getPanel() == null)
panelBinding = panelBinding.setup(bindCtx, this);
registerProjectGlobalVariables(bindCtx);
panelBinding.refreshControl();
try
jbInit();
panelBinding.refreshControl();
catch(Exception ex)
panelBinding.reportException(ex);
private void jButton1_actionPerformed(ActionEvent e)
// Get the user-supplied values
String txt = jTextField1.getText();
String[] mIds = txt.split(",");
// Now trim
for (int i=0; i<mIds.length; i++)
mIds[i] = mIds.trim();
ApplicationModule am = (ApplicationModule)panelBinding.getDataControl().getDataProvider();
EmpView vo = (EmpView)am.findViewObject("EmpView1");
vo.setManagerID(mIds);
try
vo.executeQuery();
} catch (SQLStmtException s)
System.out.println("Query failed: " + s.getMessage()); -
Can a SQL WITH Clause be used in Materialized View
Hello,
Can we use SQL WITH clause in Materialized View.
ThanksHello,
Here is an example
CREATE MATERIALIZED VIEW MV_TEST
BUILD IMMEDIATE
REFRESH FORCE ON DEMAND
AS
WITH t AS (SELECT owner, object_type, COUNT ( * )
FROM my_objects
GROUP BY object_type, owner)
SELECT *
FROM t
WHERE owner IN ('SYS', 'SYSTEM');Regards -
Searching for a better design for function in sql where clause
We are using for a while a parameter management framework based on parameter hierarchy and matrix fully internazionalized. For implementation flexibility we never use primary key to access directly the parameter but used a function that return the corresponding primary key by selecting it in an array in a package with a parameter name or external identification number that never change.
All is working well ... the system is very flexible ... we are as developper very happy because we can offer a centralized management parameter system for the whole application.
Our problem is regarding the lack of sql performance when the packaged function are used in sql ... it seem that they are executed each time for earch row instead of only once and bind to the sql (as a bind variable). This is really a big issue. We solve the problem in PL/SQL by getting the parameter in variable and bind it the sql but it is not possible everythere and we will be interesting to know if somebody had similar problem and how we may solve the problem.
Thanks a lotselect contractdate.contract_i
, contractdate.contractdate
from contractdate
, ( select contractdate.contract_i
, max( nvl( contractdate.dateto, sysdate) ) dateto
from contractdate
where contractdate.t_contractdate_i = firstexpiry
group by contract_i
) contractdatelast
where contractdate.contract_i = contractdatelast.contract_i
and nvl( contractdate.dateto, sysdate ) = nvl( contractdatelast.dateto, sysdate )
and contractdate.t_contractdate_i = t_contractdate_ipar.fgetflextypologyclassitem_i( t_contractdate_ipar.fis1stexpiry )t_contractdate_ipar.fgetflextypologyclassitem_i is the function that return the primary key corresponding to the internal identification number
t_contractdate_ipar.fis1stexpiry is the function that return the internal identification number
An array in a package contains class and items internal identification number with the corresponding primary key used in the whole application (label, description in the user language also). All data for item (parameters) are stored in the flextypologyclassitem table that is referred by all parameters in the application. An application manage this table as a centralized parameter system. -
XSQL Using bind params with sql LIKE clause
I am unable to use a bind-param with the LIKE clause in a SELECT statement.
eg call .../temp.xsql?name=N
XSQL query is this:
<xsql:query max-rows="-1" bind-params="name">
SELECT last_name
FROM emp
WHERE last_name LIKE '?%'
</xsql:query>
I have tried a few combinations so far with no success eg:
WHERE last_name LIKE '{@name}%'
WHERE last_name LIKE ?||%
Any ideas?I highly recommend using XSQL's real bind variable feature wherever you can. You can read about it in the XSQL Online Documentation (Search for the "Using Bind Variables" section).
Using this feature is more performant and more secure than using textual substitution variables.
Here's what your page looks like using textual substitution:
<page connection="UTD4" xmlns:xsql="urn:oracle-xsql">
<xsql:query null-indicator="yes" >
SELECT * FROM TC_HL7_SEG WHERE SEGMENT_CODE LIKE '{@code}%'
</xsql:query>
</page> .
And here's what it would look like using real bind variables:
<page connection="UTD4" xmlns:xsql="urn:oracle-xsql">
<xsql:query null-indicator="yes" bind-params="code">
SELECT * FROM TC_HL7_SEG WHERE SEGMENT_CODE LIKE ?||'%'
</xsql:query>
</page> .
Using real bind variables allows the database to avoid reparsing the SQL statement everytime, which improves performance.
Steve Muench
JDeveloper/BC4J Development Team
Author, Building Oracle XML Applications -
Help with SQL Query - MIN MAX - CTE?
First and foremost, the SQL is handled dynamically - please ignore some of the crazy coding you see in the WHERE clauses ... its not an issue with the report, trust me.
What my client needs is a summary by Facility, by Resource for each specific day - broken out in 3 distinct time blocks for that specific Resource at each distinct facility. For each Resource by Facility I need 3 rows - a row for their earliest AM appointment
to their latest AM appointment (AMStart and AMStop below) - a row for their earliest PM appointment to their latest PM appointment (PMStart and PMStop below) and finally a row for their EVE appointments (EVEStart and EVEStop below).
I thought doing a MIN and MAX on them would fix this and grouping it but I am missing something because my times for my AM are way off. For my test provider, I have set up a schedule that starts at 7:15 AM and spans to 11:45 AM. I created a break and had
him re-start at 1:00 PM and go to 2:45 PM. No Evening clinic was made on this example.
What I would hope to get back is 3 rows - an AM row with the earliest AMStart and latest AMStop time (with the PM and EVE pull NULL), a PM row(earliest and latest) (with the AM and EVE pull NULL) and finally my EVE with same concept.
My current data set (1 row) - should have as 3 rows and my AM Start and Stop are wrong.
Scheduledate = 01/21/2014
AMStart = 10:00AM
AMStop = 9:45AM
PMStart = 1:00PM
PMStop = 2:45PM
EveStart = NULL
EveStop = NULL
TotalTime = 375
Resource = Bailey MD, William R
Facility = River Oaks
/*Appointment Times report*/
SET NOCOUNT ON
DECLARE @Today DATETIME
DECLARE @Tomorrow DATETIME
SET @Today = '01/21/2014'
SET @Tomorrow = DATEADD(d , 1 , '01/21/2014')
DECLARE @tblTemp TABLE
ApptSlotId INT ,
Resource VARCHAR(60) ,
ResourceId INT ,
Start DATETIME ,
Stop DATETIME ,
AMStart DATETIME ,
AMStop DATETIME ,
PMStart DATETIME ,
PMStop DATETIME ,
EveStart DATETIME ,
EveStop DATETIME ,
Patient VARCHAR(256) ,
[Column] VARCHAR(64) ,
Facility VARCHAR(60) ,
FacilityId INT ,
Allocations VARCHAR(4096) ,
Scheduledate VARCHAR(15)
INSERT INTO @tblTemp
SELECT
ApptSlotid ,
d.Listname ,
d.DoctorFacilityId ,
Start ,
Stop ,
NULL ,
NULL ,
NULL ,
NULL ,
NULL ,
NULL ,
' ' AS Patient ,
CAST(aps.ListOrder AS VARCHAR(10)) AS [Column] ,
f.ListName AS Facility ,
aps.FacilityId ,
dbo.sfnGetAllocsForSlot(aps.ApptSlotId) AS Allocations ,
CONVERT(VARCHAR(15) , Start , 101)
FROM
ApptSlot aps
JOIN Schedule s ON aps.ScheduleId = s.ScheduleId
JOIN DoctorFacility df ON s.DoctorResourceId = df.DoctorFacilityId
JOIN DoctorFacility f ON aps.FacilityId = f.DoctorFacilityId
JOIN DoctorFacility d ON s.DoctorResourceId = d.DoctorFacilityId
WHERE
--Filter on resource
NULL IS NOT NULL
AND s.Doctorresourceid IN ( NULL )
OR ( NULL IS NULL )
AND (
NULL IS NOT NULL
AND aps.FacilityId IN ( NULL )
OR ( NULL IS NULL )
AND (
Start >= @Today
OR @Today IS NULL
AND (
Start < @Tomorrow
OR @Tomorrow IS NULL
AND ApptId IS NULL
AND APS.ListOrder <> -1
INSERT INTO @tblTemp
SELECT DISTINCT
ApptSlotid ,
d.ListName ,
d.DoctorFacilityId ,
ApptStart ,
ApptStop , -- need distinct because =ApptSlot can have more than row per appt
NULL ,
NULL ,
NULL ,
NULL ,
NULL ,
NULL ,
CASE WHEN a.ApptKind = 1 THEN pp.Last + ', ' + pp.First
WHEN a.ApptKind = 2 THEN 'Doctor Appt'
WHEN a.ApptKind = 3 THEN 'Resource Appt'
WHEN a.ApptKind = 5 THEN 'Block Out Appt'
ELSE ''
END AS Patient ,
CASE WHEN aps.ListOrder IS NULL THEN 'Overbooked'
ELSE CAST(aps.ListOrder AS VARCHAR(10))
END AS [Column] ,
f.ListName AS Facility ,
a.FacilityId ,
ISNULL(apt.Name , '<No Appointment Type>') AS Allocations ,
CONVERT(VARCHAR(15) , ApptStart , 101) AS Scheduledate
FROM
Appointments a
JOIN DoctorFacility f ON a.FacilityId = f.DoctorFacilityId
LEFT JOIN PatientProfile pp ON a.OwnerId = pp.PatientProfileId
LEFT JOIN ApptSlot aps ON a.AppointmentsId = aps.ApptId
JOIN DoctorFacility d ON a.ResourceId = d.DoctorFacilityId
LEFT JOIN ApptType apt ON a.ApptTypeId = apt.ApptTypeId
WHERE
NULL IS NOT NULL
AND a.ResourceId IN ( NULL )
OR ( NULL IS NULL )
AND (
NULL IS NOT NULL
AND a.FacilityId IN ( NULL )
OR ( NULL IS NULL )
AND (
ApptStart >= @Today
OR @Today IS NULL
AND (
ApptStop < @Tomorrow
OR @Tomorrow IS NULL
AND (
(ApptKind = 1
AND ISNULL(Canceled , 0) = 0)
UPDATE
@tblTemp
SET
AMStart = Start ,
AMStop = Stop
FROM
@tblTemp base
WHERE
CONVERT(TIME , start) < CONVERT(TIME , '12:00')
UPDATE
@tblTemp
SET
PMStart = Start ,
PMStop = Stop
FROM
@tblTemp base
WHERE
CONVERT(TIME , start) > CONVERT(TIME , '12:00')
AND CONVERT(TIME , start) < CONVERT(TIME , '17:00')
UPDATE
@tblTemp
SET
EveStart = Start ,
EveStop = Stop
FROM
@tblTemp base
WHERE
CONVERT(TIME , start) > CONVERT(TIME , '17:00')
--SELECT * FROM @tblTemp ORDER BY Start
SELECT
Scheduledate ,
Start ,
Stop ,
[Column] ,
Resource ,
Facility ,
CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.AMStart , 108) AS TIME) , 100) AS AMStart ,
CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.AMStop , 108) AS TIME) , 100) AS AMStop ,
CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.PMStart , 108) AS TIME) , 100) AS PMStart ,
CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.PMStop , 108) AS TIME) , 100) AS PMStop ,
CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.EveStart , 108) AS TIME) , 100) AS EveStart ,
CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.EveStop , 108) AS TIME) , 100) AS EveStop ,
ISNULL(DATEDIFF(MI , h.AMStart , h.AMStop) , 0) + ISNULL(DATEDIFF(MI , h.PMStart , h.PMStop) , 0) + ISNULL(DATEDIFF(MI , h.EveStart , h.EveStop) , 0) AS TotTime
INTO
#tmp
FROM
@TblTemp h
WHERE
[Column] = 1
ORDER BY
START
--SELECT * FROM #tmp
SELECT
Scheduledate ,
MIN(AMStart) AS AMStart ,
MAX(AMStop) AS AMStop ,
MIN(PMStart) AS PMStart ,
MAX(PMStop) AS PMStop ,
MIN(EveStart) AS EveStart ,
MAX(EveStop) AS EveStop ,
SUM(TotTime) AS TotalTime ,
Resource ,
Facility
FROM
#tmp
GROUP BY
Resource ,
Facility ,
Scheduledate
DROP TABLE #tmp
SET NOCOUNT OFFSince there is some context missing, I don't get everything, but from your narrative, it seems likely you need something like:
WITH CTE AS (
SELECT keycol,
period = CASE WHEN Start < '12:00' THEN 'AM'
WHEN Start < '17:00' THEN 'PM'
ELSE 'EVE'
END,
start, stop
FROM tbl
SELECT keycol, period, MIN(start), MAX(stop)
FROM CTE
GROUP BY keycol, period
Erland Sommarskog, SQL Server MVP, [email protected] -
Using sql functions (min, max, avg) on varray or table collection
Hi,
I would like to know if there is a way to use sql function or oracle sql function like Min,Max, Avg or percentile_cont on varray or table collection ?
Does anyone encountered this type of problem ?
ThanksYes you can apply Min,Max, Avg... if varray or table collection type is SQL (created in the databaase) UDF, not PL/SQL declared type:
SQL> set serveroutput on
SQL> declare
2 type str_tbl_type is table of varchar2(4000);
3 str_tbl str_tbl_type := str_tbl_type('X','A','D','ZZZ');
4 max_val varchar2(4000);
5 begin
6 select max(column_value)
7 into max_val
8 from table(str_tbl);
9 dbms_output.put_line('Max value is "' || max_val || '"');
10 end;
11 /
from table(str_tbl);
ERROR at line 8:
ORA-06550: line 8, column 18:
PLS-00642: local collection types not allowed in SQL statements
ORA-06550: line 8, column 12:
PL/SQL: ORA-22905: cannot access rows from a non-nested table item
ORA-06550: line 6, column 5:
PL/SQL: SQL Statement ignored
SQL> create or replace type str_tbl_type is table of varchar2(4000);
2 /
Type created.
SQL> declare
2 str_tbl str_tbl_type := str_tbl_type('X','A','D','ZZZ');
3 max_val varchar2(4000);
4 begin
5 select max(column_value)
6 into max_val
7 from table(str_tbl);
8 dbms_output.put_line('Max value is "' || max_val || '"');
9 end;
10 /
Max value is "ZZZ"
PL/SQL procedure successfully completed.
SQL> SY. -
Apex 4.0 Image Buttons to update SQL Where clause of Report?
I made a table called Letters with 1 column in it called Letter and the data in it is simply A,B,C, to H. I made an apex form around this table and then created two image buttons A and B that display above the reporting area b/c i want to be able to click on the A image button and have it update the Where clause for the Letters table to be "Where Letter = A" (so once you click the A button, only the A will appear), same for the B button. I have attached a link to an album of images to show what i'm trying to do to better explain it. I just can't figure out what or how to make it so that the image button can update the where clause. I should note that i am relatively new to Apex and i tried using a dynamic action to do it but can't get this to work.
Link to images of what i have so far-> http://imgur.com/a/guxkd/oracle_apex_40_use_image_buttons
Any suggestions?
Edited by: Brobot on Feb 8, 2011 9:58 PMSince you are using some kind of button(with images or otherwise) , add some attributes to identify them together aswell as uniquely.
For instance if you add a name and an a common classname to each button
For example, in button attributes for A this could be
name="A" class="where_clause_button"You can use these attributes to trigger a Dynamic action which can refresh the report.
Since you want the report to be filtered based on the button(ie using the "name" attribute of the corresponding button) , you need to set that value in some hidden item, say P100_FILTER_LETTER. and add a where clase to your Report Region' SQL Query
WHERE <column name> = :P100_FILTER_LETTERNow create a Dynamic Action as
Event :Click
Triggering Element : jQuery selector
Selector : *.where_clause_button*
<li>True action 1 : Execute Javascript code
filter_item_name = 'P100_FILTER_LETTER'
this_button_name = $(this.triggeringElement).attr('name');
//Set session state of Hidden Item before refresh
var ajaxRequest=new htmldb_Get(null,$v('pFlowId'),'null',$v('pFlowStepId'));
ajaxRequest.add( filter_item_name ,this_button_name );
var ajaxResult=ajaxRequest.get();<li> True Action 2: Refresh
Affected Element: Region
Name : Choose Report Region Name
Hope it helps -
Report- Pl/sql function returning sql query parsing page items as text?
Hi Team,
I am facing a strange issue .
I have four page items namely
1)JOB_CODE
2)MIN_EXP
3) MAX_EXP
4) SOURCES1
I have a report of the type "Pl/sql function returning sql query"
declare
v_sql varchar2(4000);
begin
if (:JOB_CODE IS NOT NULL and :MIN_EXP IS NOT NULL and :MAX_EXP IS NOT NULL and :SOURCES1 IS NOT NULL) then
v_sql:= 'select v_candidate_id, v_fname,v_current_employer,v_Experience_years from candidature where V_REQUIREMENT = :JOB_CODE and v_experience_years >= :MIN_EXP and v_experience_years <= :MAX_EXP and source like ' || '''' || '%'|| ':SOURCES1' || '%' || '''';
elsif (:JOB_CODE IS NULL and :MIN_EXP IS NOT NULL and :MAX_EXP IS NOT NULL and :SOURCES1 IS NOT NULL) then
v_sql := 'select v_candidate_id, v_fname,v_current_employer,v_Experience_years from candidature where v_experience_years >= :MIN_EXP and v_experience_years <= :MAX_EXP and source like ' || '''' || '%'|| ':SOURCES1' || '%' || '''';
elsif (:MIN_EXP IS NULL and :JOB_CODE IS NOT NULL and :MAX_EXP IS NOT NULL and :SOURCES1 IS NOT NULL) then
v_sql := 'select v_candidate_id, v_fname,v_current_employer,v_Experience_years from candidature where v_experience_years <= :MAX_EXP and V_REQUIREMENT = :JOB_CODE and source like ' || '''' || '%'|| ':SOURCES1' || '%' || '''';
elsif (:MAX_EXP is null and :JOB_CODE IS NOT NULL and :MIN_EXP IS NOT NULL and :SOURCES1 IS NOT NULL) then
v_sql := 'select v_candidate_id, v_fname,v_current_employer,v_Experience_years from candidature where V_REQUIREMENT = :JOB_CODE and v_experience_years >= :MIN_EXP and source like ' || '''' || '%'|| ':SOURCES1' || '%' || '''';
end if;
insert into query_list values (v_sql);
insert into debug values (:JOB_CODE , :MIN_EXP , :MAX_EXP , :SOURCES1);
return v_sql;
end;
Please not that I am insertin the query into a table called Query_list and the page item values into the table called Debug thru the pl/sql function which returns teh query.
Now I select the data from the debug tables.
select unique(query) from query_list;
select v_candidate_id, v_fname,v_current_employer,v_Experience_years from candidature where V_REQUIREMENT = :JOB_CODE and v_experience_years >= :MIN_EXP and v_experience_years <= :MAX_EXP and source like '%:SOURCES1%'
select * from debug;
JOBCODE MINEX MAXEX SOURCE
21 1 10 donkeyHire
And if I run the query in sql I get some records returned
select v_candidate_id, v_fname,v_current_employer,v_Experience_years from candidature where V_REQUIREMENT = 21 and v_experience_years >= 1 and v_experience_years <= and source like 'donkeyHire'
V_CANDIDATE_ID V_FNAME V_CURRENT_EMPLOYER V_EXPERIENCE_YEARS
2 Vengu Andale Tech 4
But the record does not show up in the report!
does this type of report parse page items as text?
Why is it so?
Waiting for an early reply.
Thanks,
venkatVenkat - You don't want to put ':SOURCES1' in quotes like that.
Scott -
Exclude duplicate values on SQL where clause statement
Hi!
Are some posibilities to exclude duplicate values do not using sql aggregate functions in main select statement?
Priview SQL statement
SELECT * FROM
select id,hin_id,name,code,valid_date_from,valid_date_to
from diaries
QRSLT
WHERE (hin_id = (SELECT NVL(historic_id,id)FROM tutions where id=/*???*/ 59615))
AND NVL(valid_date_to,to_date('22.12.2999','dd.mm.yyyy')) <= (SELECT NVL(valid_date_to,to_date('22.12.2999','dd.mm.yyyy'))FROM tutions where id= /*???*/ 59615)
AND trunc(valid_date_from) >=(SELECT trunc(valid_date_from)FROM tutions where id= /*???*/ 59615)
The result
ID HIN_ID NAME CODE VALID_DATE FROM VALID_DATE_TO
50512
59564
RE TU
01
07.06.2013 16:32:15
07.06.2013 16:33:28
50513
59564
TT2
02
07.06.2013 16:33:23
07.06.2013 16:33:28
50515
59564
TT2
02
07.06.2013 16:33:28
07.06.2013 16:34:42
50516
59564
ROD
03
07.06.2013 16:34:37
07.06.2013 16:34:42
VALID_DATE_TO & AND VALID_DATE_FROM tutions
07.06.2013 16:34:42
15.07.2013 10:33:23
In this case i got duplicate of entry TT2 id 50513 In main select statement cant use agregate functions are even posible to exclude this value from result modifying only the QLRST WHERE clause (TRUNC need to be here)
THANKS FOR ANY TIP !
ID.Hi, Ok this is working in this case
SELECT * FROM
select id,hin_id,name,code,valid_date_from,valid_date_to
from diaries ahs
QRSLT
WHERE (hin_id = (SELECT NVL(historic_id,id)FROM aip_healthcare_tutions where id=/*???*/ 59615))
AND NVL(valid_date_to,to_date('22.12.2999','dd.mm.yyyy')) <= (SELECT NVL(valid_date_to,to_date('22.12.2999','dd.mm.yyyy'))FROM tutions where id= /*???*/ 59615)
AND trunc(valid_date_from) >=(SELECT trunc(valid_date_from)FROM tutions where id= /*???*/ 59615)
AND NOT EXISTS
(SELECT null FROM diaries ahs WHERE ahs.valid_date_from < QRSLT.valid_date_from
AND QRSLT.hin_id=ahs.hin_id
AND QRSLT.code=ahs.code);
Result
50512
59564
RE TU
01
07.06.2013 16:32:15
07.06.2013 16:33:28
50513
59564
TT2
02
07.06.2013 16:33:23
07.06.2013 16:33:28
50516
59564
ROD
03
07.06.2013 16:34:37
07.06.2013 16:34:42
But if the Data in tutions row are theese(valid_date_to-null) then NO ROWS are returning and its logical because in full result list Valid_date_from column are logical incorect
valid_date_from valid_date_to
15.07.2013 10:33:23
NULL
ID HIN_ID NAME CODE VALID_DATE FROM VALID_DATE_TO
50510
59564
RE TU
01
07.06.2013 16:33:28
50511
59564
TT2
02
07.06.2013 16:34:41
50514
59564
ROD
03
07.06.2013 16:34:41
50520
59564
Params
04
03.07.2013 21:01:30
50512
59564
RE TU
01
07.06.2013 16:32:15
07.06.2013 16:33:28
50513
59564
TT2
02
07.06.2013 16:33:23
07.06.2013 16:33:28
50515
59564
TT2
02
07.06.2013 16:33:28
07.06.2013 16:34:42
50516
59564
ROD
03
07.06.2013 16:34:37
07.06.2013 16:34:42
Are that posible modifying where statement if the valid_date_to in tutions are null then theese records where in diary valid_date_to is null is correct to, but need to stay previos logic
D HIN_ID NAME CODE VALID_DATE FROM VALID_DATE_TO
50510
59564
RE TU
01
07.06.2013 16:33:28
null
50511
59564
TT2
02
07.06.2013 16:34:41
null
50514
59564
ROD
03
07.06.2013 16:34:41
null
50520
59564
Params
04
03.07.2013 21:01:30
null
Thanks !
ID.
Maybe you are looking for
-
Queries related to MAM configuration and MI synchronization
Hi, I have queries as to the synchronization in MI & MAM 1. When I am synchronizing with MI Server, the requests are going in I-Waiting work lists in work list monitor.. What could be the reason for it. 2. I require clarification as to exact purpos
-
I upgraded to a new version of iweb and had to re-configure my site. The name of the site was the same except that I capitalized the first letter in my first and last name. Now I have two sites. One has my old information and one has the updated info
-
Hi gurus, Is there anything available to monitor programming, configuration or database changes to SAP in the production environment (e.g., activity reports)? Let me know if I am not clear about my question Thanks in advance Ravi Bopp
-
Hi, I am implementing a BADI in the BP transaction on the R/3 side. For a certain select statement in the BADi, I am doing a sy-subrc <> 0 check, and if it is not equal to 0, I need to raise an exception. I am raising an exception of type E. The popu
-
Is anyone else having problems with apps after the ios6 install? Many of mine just close when i try to use them.