SQL queries in one statement with derby
Hi,
I am using a derby embedded database and i need to create a database at the installation. So i need to create a lot of tables.
But it seems like I have to create a statement for each create table query. Is this true? Isn't there a way to execute all of them in one statement ?
Thank you
Hi,
I am using a derby embedded database and i need to
create a database at the installation. So i need to
create a lot of tables.Hi,
Database should be created by yourself after setting security constraints .
But it seems like I have to create a statement for
each create table query. Is this true?Yes. You need to create one statement for one query to execute.
thanks,
nvseenu
Similar Messages
-
Executing Multiple SQL queries in one connection
I'm trying to do, 2 queries in a single connection to my MySQL database.
At the moment I'm just passing a String into execute query.
I want to do another check in the database just after I get the first query's results.
Right now, I'm closing the connection and creating a whole new one again as it doesn't seem to work otherwise.
Do I just need to create a new "Statement" & "ResultSet" and then do my thing within the connection brackets?
I did that but was getting no response. Perhaps I'm missing something?
Code to SELECT all Documentaries from the database:
String getDocs = "SELECT * from podDir WHERE genre='Documentaries'";
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/jspod", "root", "pass");
System.out.println("got connection");
Statement s = con.createStatement();
ResultSet r2 = s.executeQuery(getDocs);
while (r2.next()) {
out.println("<TD>" + StringUtil.encodeHtmlTag(r2.getString(1)) + "</TD>");
out.println("<TD><A href='" + StringUtil.encodeHtmlTag(r2.getString(3)) + "'>" + StringUtil.encodeHtmlTag(r2.getString(2)) + "</a></TD>");
out.println("<TD>" + StringUtil.encodeHtmlTag(r2.getString(4)) + "</TD>");
out.println("<TD>Subscribe</TD>");
out.println("</TR>");
out.println("<TR><TD></TD><TD>" + StringUtil.encodeHtmlTag(r2.getString(6)) + "</TD>");
out.println("</TR>");
r2.close();
s.close();
con.close();
catch (SQLException e) {
catch (Exception e) {
}Thanks ram..
I'm now finding I'm facing a situation, however where
I need two executions ongoing at one time.
I need to select all listings from a directory table
and then check if the person logged in has subscribed
to that listing from a "Mysubs" table concurrently to
display "You are/not subscribed to this
listing".
Is it possible to have two ongoing executions?Some would prefer to do all that in a single query - but then one has to be pretty good in sql for that.
You can do the stuff with 2 or more queries too. Open a Connection, create a PreparedStatement(or a Statement) with your first query for the listings. Get the result set, hold the output in a ListingModel object. You would then close the result set and the statement and then open new ones for your second query which can be supplemented with data from the model object. Or you can retrieve the entire data and compare with the listing info in the ListingModel object. Close everything in a finally block.
ram. -
Two Queries In One Workbook With Calculations
Hi Guys,
Can you have 2 queries in one worksheet, either ran as a query or save as a workbook and calculation done at runtime. For example, query A and query B to show up in one sheet when you run query A. You now want a simple calculation done......for example.......A1 row from query A divided by B1 row from query B. The result to show up on the Key Figure structure in query A.
Thanks,
Recca
Edited by: Recca Recca on Jul 11, 2011 4:45 PMHi,
I am not sure about this but we had similar kind of requirement and what we did was,
One query in one tab, another query on second tab and we did key figure calculations on third tab of the workbook eg. Sheet1 A1 - Sheet2-A1 and the result was stored on sheet3.
We saved the workbook and used to refresh the same whenever we want to see new data.
Regards,
Durgesh. -
? in SQL Queries and not using prepared statements
Using EclipseLink 1.1.1
Prepared Statements are disabled
In our production server something went wrong and one of our Read Queries started erroring. A DatabaseException was thrown and we log the "getQuery.getSQLString()" statement. We found this query in the logs:
SELECT t1.ID, t1.NAME, t1.DESCRIPTION, t1.EXTREFID, t1.STYLESHEET, t1.DDSVNVERSION, t1.FIRSTNAME, t1.LASTNAME, t1.EMAILADDR, t1.PHONENUMBER, t1.ADDRESS, t1.ADDRESS2, t1.CITY, t1.STATE, t1.POSTALCODE, t1.COUNTRY, t1.ADMINACCTNAME, t1.HASDOCUMENTS, t1.HASTIMEDNOTIFICATIONS, t1.STATUS, t1.ENTRYDATE, t1.EVALEXPDATE, t1.LASTREMINDDATE, t1.FULLUSERS, t1.LIMUSERS, t1.REQUSERS, t1.ISENTERPRISE, t1.EXPDATE, t1.ISDISABLED, t1.DISABLEDDATE, t1.NEEDLICENSEAGREEMENT, t1.ISWARNINGDISABLED, t1.LOCALE, t1.TIMEZONE, t1.CURRENCY, t1.DOMAIN, t1.DOCUMENTSIZE, t1.EXTRADOCUMENTSTORAGE, t1.ONDEMANDOPTIONS, t1.SSOTYPE, t1.RESELLERID, t1.ACCOUNTREPID, t1.LASTUSAGEREPORTDATE, t1.NEXTUSAGEREPORTDATE, t1.USAGEREPORTATTEMPTS FROM T_SSOOPTIONS t0, T_CUSTOMERS t1 WHERE *((((t0.SSOENABLED = ?) AND (t1.SSOTYPE IN (?, ?))) AND (UPPER(t1.DOMAIN) = ?)) AND (t0.CUSTOMERID = t1.ID))*
Notice the values weren't entered into the where clause. We had to bounce the application to fix the problem. I've never seen this before. I've added more debugging statements to the code - so if this happens again in the future I'll have more information to report on. In the mean time I'm wondering if anyone else has every seen a problem of this nature.Database error due to invalid SQL statement.
I don't have a stack, we were catching the exception and not printing the stack :(
Like I mentioned in my first post, I added more debugging code (e.printStackTrace()). I understand this is hard to track down without more information. I was just hoping you guys had seen something like this before and had any insight. Like I mentioned before: this is on our production server. I've never seen this type of error before. That particular server (we run in a cluster mode) had been up for several days and then started generating that error. IT bounced the node and everything went back to normal. We have been using toplink for about 5 years now and have never seen this problem, until August 3rd 2009. The only thing that has changed recently is our migration from toplink 10 to EclipseLink. I was wondering if anyone knows if anything had changed in EclipseLink/toplink 11 with the generation of SQL queries.
I'll keep looking. There is more debugging code in there now. Since the error was "Database error due to invalid SQL statement" this implies the SQL was generated, exited that part of the code and was sent to the db where it failed. I'm afraid the printStackTrace won't help if this error happens again. -
SQL statement with LIMIT and total count?
Hello,
I would like to know if it is possible to execute a single SQL statement that will return me a subset of data (for pagination purposes) that not only includes the subset of data for the page but the count of all available data. Can this be done so as to not take up the cpu and time it takes to essentially run two queries? One to get the subset and one to get the count? I think simply doing a subselect is not going to give me what I want in that we actually query twice.
There may be no way to do this other than that, but I wanted to check with the gurus here first. :)
Thanks,
Markselect *
from (
select i.*,
row_number() over(order by i) rn, -- used for
pagination
count(*) over(partition by 1) cnt -- total count
of rows found for this search
from mytable
where < PUT ALL LIMITING (i.e., "search") CONDITIONS
HERE >
where rn between 41 and 50 -- pagination clauseNice one
BUT of course it adds additional row in execution plan and takes additional time and CPU :)
I assume that it directly depends of course on returned result set and some other factors like available sort space but a simple test case on a table big which actually is 1.6 M rows like dba_source got following results:
here is the first one returning also count(*)
SQL> select *
2 from (
3 select i.*,
4 row_number() over(order by owner, name, type) rn
5 , -- used for pagination
6 count(*) over(partition by 1) cnt -- total count of rows found for this search
7 from big i
8 where owner like 'S%' and name like '%A%'
9 )
10 where rn between 41 and 45
11 /
OWNER NAME TYPE
LINE
TEXT
RN CNT
SYS ANYDATA TYPE
13
STATIC FUNCTION ConvertVarchar(c IN VARCHAR) return AnyData,
41 999744
SYS ANYDATA TYPE
11
STATIC FUNCTION ConvertDate(dat IN DATE) return AnyData,
42 999744
SYS ANYDATA TYPE
9
43 999744
SYS ANYDATA TYPE
7
They serve as explicit CAST functions from any type in the Oracle ORDBMS
44 999744
SYS ANYDATA TYPE
6
enable construction of the AnyData in its entirity with a single call.
45 999744
Elapsed: 00:00:41.02
SQL> ed
Wrote file afiedt.buf
1 select n.name, m.value from v$statname n, v$mystat m
2 where n.statistic# = m.statistic#
3* and (upper(name) like '%SORT%' or upper(name) like '%TEMP%')
SQL> /
NAME VALUE
physical reads direct temporary tablespace 35446
physical writes direct temporary tablespace 17723
RowCR attempts 0
SMON posted for dropping temp segment 0
sorts (memory) 36
sorts (disk) 1
sorts (rows) 1999596
OTC commit optimization attempts 0
8 rows selected.here is the second one returning only rows:
SQL> ed
Wrote file afiedt.buf
1 select *
2 from (
3 select i.*,
4 row_number() over(order by owner, name, type) rn
5 --, -- used for pagination
6 -- count(*) over(partition by 1) cnt -- total count of rows found for this search
7 from big i
8 where owner like 'S%' and name like '%A%'
9 )
10* where rn between 41 and 45
SQL> /
OWNER NAME TYPE
LINE
TEXT
RN
SYS ANYDATA TYPE
13
STATIC FUNCTION ConvertVarchar(c IN VARCHAR) return AnyData,
41
SYS ANYDATA TYPE
11
STATIC FUNCTION ConvertDate(dat IN DATE) return AnyData,
42
SYS ANYDATA TYPE
9
43
SYS ANYDATA TYPE
7
They serve as explicit CAST functions from any type in the Oracle ORDBMS
44
SYS ANYDATA TYPE
6
enable construction of the AnyData in its entirity with a single call.
45
Elapsed: 00:00:12.09
SQL> select n.name, m.value from v$statname n, v$mystat m
2 where n.statistic# = m.statistic#
3 and (upper(name) like '%SORT%' or upper(name) like '%TEMP%')
4 /
NAME VALUE
physical reads direct temporary tablespace 0
physical writes direct temporary tablespace 0
RowCR attempts 0
SMON posted for dropping temp segment 0
sorts (memory) 10
sorts (disk) 0
sorts (rows) 999812
OTC commit optimization attempts 0
8 rows selected.So execution time 41 sec vs 12 sec
sorts (rows) 1 999 596 vs 999 812
physical reads/writes direct temporary tablespace 35446/17723 vs 0/0
I assume that for a small overall returned row count it probably is OK, but for less restrictive search it can be quite deadly as before with two queries.
Gints Plivna
http://www.gplivna.eu -
Scaleability with Functions in SQL queries
Hi,
In one of our applications we have many views that use a packaged function in the where clause to filter data. This function uses a SYS_CONTEXT() to set and get values. There are couple of issues while using this approach:
1/ The deterministic function doesn't allow any scability with PQ-server.
2/ Another issue with this function and also the SYS_CONTEXT-function, they manuipulate the estimated CBO-statistics.
CREATE TABLE TAB_I
COLUMN1 NUMBER(16, 0) NOT NULL
, COLUMN2 VARCHAR2(20)
, CONSTRAINT TAB_I_PK PRIMARY KEY
COLUMN1
ENABLE
CREATE TABLE TAB_V
I_COL1 NUMBER(16,0) NOT NULL ENABLE,
VERSION_ID NUMBER(16,0) NOT NULL ENABLE,
CRE_DATIM TIMESTAMP (6) NOT NULL ENABLE,
TERM_DATIM TIMESTAMP (6) NOT NULL ENABLE,
VERSION_VALID_FROM DATE NOT NULL ENABLE,
VERSION_VALID_TILL DATE NOT NULL ENABLE,
CONSTRAINT TAB_V_PK PRIMARY KEY (I_COL1, VERSION_ID) USING INDEX NOCOMPRESS LOGGING ENABLE,
CONSTRAINT COL1_FK FOREIGN KEY (I_COL1) REFERENCES TAB_I (COLUMN1) ENABLE
CREATE OR REPLACE
PACKAGE app_bitemporal_rules IS
FUNCTION f_knowledge_time RETURN TIMESTAMP DETERMINISTIC;
END app_bitemporal_rules;
create or replace
PACKAGE BODY app_bitemporal_rules IS
FUNCTION f_knowledge_time RETURN TIMESTAMP DETERMINISTIC IS
BEGIN
RETURN TO_TIMESTAMP(SYS_CONTEXT ('APP_USR_CTX', 'KNOWLEDGE_TIME'),'DD.MM.YYYY HH24.MI.SSXFF');
END f_knowledge_time;
END app_bitemporal_rules;
explain plan for select *
FROM tab_i
JOIN tab_v
ON tab_i.column1 = tab_v.i_col1
AND app_bitemporal_rules.f_knowledge_time BETWEEN tab_v.CRE_DATIM AND tab_v.TERM_DATIM
where tab_i.column1 = 11111;
select * from table(dbms_xplan.display);
Plan hash value: 621902595
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 95 | 5 (0)| 00:00:06 |
| 1 | NESTED LOOPS | | 1 | 95 | 5 (0)| 00:00:06 |
| 2 | TABLE ACCESS BY INDEX ROWID| TAB_I | 1 | 25 | 1 (0)| 00:00:02 |
|* 3 | INDEX UNIQUE SCAN | TAB_I_PK | 1 | | 1 (0)| 00:00:02 |
|* 4 | TABLE ACCESS FULL | TAB_V | 1 | 70 | 4 (0)| 00:00:05 |
Predicate Information (identified by operation id):
3 - access("TAB_I"."COLUMN1"=11111)
4 - filter("TAB_V"."I_COL1"=11111 AND
"TAB_V"."CRE_DATIM"<="APP_BITEMPORAL_RULES"."F_KNOWLEDGE_TIME"() AND
"TAB_V"."TERM_DATIM">="APP_BITEMPORAL_RULES"."F_KNOWLEDGE_TIME"())
Note
- 'PLAN_TABLE' is old version
- dynamic sampling used for this statement (level=2)
explain plan for select *
FROM tab_i
JOIN tab_v
ON tab_i.column1 = tab_v.i_col1
AND '10-OCT-2011' BETWEEN tab_v.CRE_DATIM AND tab_v.TERM_DATIM
where tab_i.column1 = 11111;
select * from table(dbms_xplan.display);
Plan hash value: 621902595
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 256 | 24320 | 5 (0)| 00:00:06 |
| 1 | NESTED LOOPS | | 256 | 24320 | 5 (0)| 00:00:06 |
| 2 | TABLE ACCESS BY INDEX ROWID| TAB_I | 1 | 25 | 1 (0)| 00:00:02 |
|* 3 | INDEX UNIQUE SCAN | TAB_I_PK | 1 | | 1 (0)| 00:00:02 |
|* 4 | TABLE ACCESS FULL | TAB_V | 256 | 17920 | 4 (0)| 00:00:05 |
Predicate Information (identified by operation id):
3 - access("TAB_I"."COLUMN1"=11111)
4 - filter("TAB_V"."I_COL1"=11111 AND "TAB_V"."CRE_DATIM"<=TIMESTAMP'
2011-10-10 00:00:00.000000000' AND "TAB_V"."TERM_DATIM">=TIMESTAMP' 2011-10-10
00:00:00.000000000')
Note
- 'PLAN_TABLE' is old version
- dynamic sampling used for this statement (level=2) As can be seen in the second plan the cardinality has been guessed correctly, but not in the first case.
I have also tried with:
ASSOCIATE STATISTICS WITH packages app_bitemporal_rules DEFAULT COST (1000000/*246919*/,1000,0) DEFAULT SELECTIVITY 50;
But, this just leads to a increased cost, but no change in cardinality.
The (1) problem gets solved if I directly use "TO_TIMESTAMP(SYS_CONTEXT ('APP_USR_CTX', 'KNOWLEDGE_TIME'),'DD.MM.YYYY HH24.MI.SSXFF')" in the where clause. But am not able to find a solution for the (2) issue.
Can you please help.
Regards,
Vikram RHi Vikram,
On the subject of using [url http://download.oracle.com/docs/cd/E11882_01/server.112/e26088/statements_4006.htm#i2115932]ASSOCIATE STATISTICS, having done a little investigation on 11.2.0.2, I'm having trouble adjusting selectivity via "associate statististics ... default selectivity" but no problems with adjusting default cost.
I've also tried to do the same using an interface type and am running into other issues.
It's not functionality that I'm overly familiar with as I try to avoid/eliminate using functions in predicates.
Further analysis/investigation required.
Including test case of what I've done so far in case anyone else wants to chip in.
SQL> select * from v$version;
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
PL/SQL Release 11.2.0.2.0 - Production
CORE 11.2.0.2.0 Production
TNS for Linux: Version 11.2.0.2.0 - Production
NLSRTL Version 11.2.0.2.0 - Production
SQL> drop table t1;
Table dropped.
SQL>
SQL> create table t1
2 as
3 select rownum col1
4 from dual
5 connect by rownum <= 100000;
Table created.
SQL>
SQL> exec dbms_stats.gather_table_stats(USER,'T1');
PL/SQL procedure successfully completed.
SQL>
SQL> create or replace function f1
2 return number
3 as
4 begin
5 return 1;
6 end;
7 /
Function created.
SQL>
SQL> create or replace function f2 (
2 i_col1 in number
3 )
4 return number
5 as
6 begin
7 return 1;
8 end;
9 /
Function created.
SQL> Created one table with 100000 rows.
Two functions - one without arguments, one with (for later).
With no associations:
SQL> select * from user_associations;
no rows selected
SQL> Run a statement that uses the function:
SQL> select count(*) from t1 where col1 >= f1;
COUNT(*)
100000
SQL> select * from table(dbms_xplan.display_cursor);
PLAN_TABLE_OUTPUT
SQL_ID gm7ppkbzut114, child number 0
select count(*) from t1 where col1 >= f1
Plan hash value: 3724264953
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 139 (100)| |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL| T1 | 5000 | 25000 | 139 (62)| 00:00:01 |
Predicate Information (identified by operation id):
2 - filter("COL1">="F1"())
19 rows selected.
SQL> Shows that default selectivity of 5% for an equality predicate against function.
Let's try to adjust the selectivity using associate statistics - the argument for selectivity should be a percentage between 0 and 100:
(turning off cardinality feedback for clarity/simplicity)
SQL> alter session set "_optimizer_use_feedback" = false;
Session altered.
SQL>
SQL> ASSOCIATE STATISTICS WITH FUNCTIONS f1 default selectivity 100;
Statistics associated.
SQL> select count(*) from t1 where col1 >= f1;
COUNT(*)
100000
SQL> select * from table(dbms_xplan.display_cursor);
PLAN_TABLE_OUTPUT
SQL_ID gm7ppkbzut114, child number 1
select count(*) from t1 where col1 >= f1
Plan hash value: 3724264953
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 139 (100)| |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL| T1 | 5000 | 25000 | 139 (62)| 00:00:01 |
Predicate Information (identified by operation id):
2 - filter("COL1">="F1"())
19 rows selected.
SQL> Didn't make any difference to selectivity.
An excerpt from a 10053 trace file had the following:
** Performing dynamic sampling initial checks. **
** Dynamic sampling initial checks returning FALSE.
No statistics type defined for function F1
No default cost defined for function F1So, crucially what's missing here is a clause saying:
No default selectivity defined for function F1But there's no other information that I could see to indicate why it should be discarded.
Moving on, adjusting the cost does happen:
SQL>exec spflush;
PL/SQL procedure successfully completed.
SQL> disassociate statistics from functions f1;
Statistics disassociated.
SQL>
SQL> ASSOCIATE STATISTICS WITH FUNCTIONS f1 default selectivity 100 default cost (100,5,0);
Statistics associated.
SQL> select count(*) from t1 where col1 >= f1;
COUNT(*)
100000
SQL> select * from table(dbms_xplan.display_cursor);
PLAN_TABLE_OUTPUT
SQL_ID gm7ppkbzut114, child number 0
select count(*) from t1 where col1 >= f1
Plan hash value: 3724264953
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 500K(100)| |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL| T1 | 5000 | 25000 | 500K (1)| 00:41:41 |
Predicate Information (identified by operation id):
2 - filter("COL1">="F1"())
19 rows selected.
SQL> And we see the following in a 10053:
No statistics type defined for function F1
Default costs for function F1 CPU: 100, I/O: 5So, confirmation that default costs for function were found and applied but nothing else about selectivity again.
I wondered whether the lack of arguments for function F1 made any difference, hence function F2.
Didn't seem to:
Vanilla:
SQL> select count(*) from t1 where col1 >= f2(col1);
COUNT(*)
100000
SQL>
SQL> select * from table(dbms_xplan.display_cursor);
PLAN_TABLE_OUTPUT
SQL_ID 2wxw32wadgc1v, child number 0
select count(*) from t1 where col1 >= f2(col1)
Plan hash value: 3724264953
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 139 (100)| |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL| T1 | 5000 | 25000 | 139 (62)| 00:00:01 |
Predicate Information (identified by operation id):
2 - filter("COL1">="F2"("COL1"))
19 rows selected.
SQL> Plus association:
SQL>exec spflush;
PL/SQL procedure successfully completed.
SQL>
SQL> associate statistics with functions f2 default selectivity 90 default cost (100,5,0);
Statistics associated.
SQL> select count(*) from t1 where col1 >= f2(col1);
COUNT(*)
100000
SQL>
SQL> select * from table(dbms_xplan.display_cursor);
PLAN_TABLE_OUTPUT
SQL_ID 2wxw32wadgc1v, child number 0
select count(*) from t1 where col1 >= f2(col1)
Plan hash value: 3724264953
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 500K(100)| |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL| T1 | 5000 | 25000 | 500K (1)| 00:41:41 |
Predicate Information (identified by operation id):
2 - filter("COL1">="F2"("COL1"))
19 rows selected.
SQL> Just to confirm associations:
SQL> select * from user_associations;
OBJECT_OWNER OBJECT_NAME COLUMN_NAME OBJECT_TY
STATSTYPE_SCHEMA STATSTYPE_NAME DEF_SELECTIVITY DEF_CPU_COST DEF_IO_COST DEF_NET_COST
INTERFACE_VERSION MAINTENANCE_TY
RIMS F2 FUNCTION
90 100 5
0 USER_MANAGED
RIMS F1 FUNCTION
100 100 5
0 USER_MANAGED
SQL> So.... started thinking about whether using an interface type would help?
SQL> CREATE OR REPLACE TYPE test_stats_ot AS OBJECT
2 (dummy_attribute NUMBER
3 ,STATIC FUNCTION ODCIGetInterfaces (
4 ifclist OUT SYS.ODCIObjectList
5 ) RETURN NUMBER
6 ,STATIC FUNCTION ODCIStatsSelectivity (
7 pred IN SYS.ODCIPredInfo,
8 sel OUT NUMBER,
9 args IN SYS.ODCIArgDescList,
10 strt IN NUMBER,
11 stop IN NUMBER,
12 --i_col1 in NUMBER,
13 env IN SYS.ODCIEnv
14 ) RETURN NUMBER
15 --,STATIC FUNCTION ODCIStatsFunctionCost (
16 -- func IN SYS.ODCIPredInfo,
17 -- cost OUT SYS.ODCICost,
18 -- args IN SYS.ODCIArgDescList,
19 -- i_col1 in NUMBER,
20 -- env IN SYS.ODCIEnv
21 -- ) RETURN NUMBER
22 );
23 /
Type created.
SQL> CREATE OR REPLACE TYPE BODY test_stats_ot
2 AS
3 STATIC FUNCTION ODCIGetInterfaces (
4 ifclist OUT SYS.ODCIObjectList
5 ) RETURN NUMBER
6 IS
7 BEGIN
8 ifclist := sys.odciobjectlist(sys.odciobject('SYS','ODCISTATS2'));
9 RETURN odciconst.success;
10 END;
11 STATIC FUNCTION ODCIStatsSelectivity
12 (pred IN SYS.ODCIPredInfo,
13 sel OUT NUMBER,
14 args IN SYS.ODCIArgDescList,
15 strt IN NUMBER,
16 stop IN NUMBER,
17 --i_col1 in NUMBER,
18 env IN SYS.ODCIEnv)
19 RETURN NUMBER
20 IS
21 BEGIN
22 sel := 90;
23 RETURN odciconst.success;
24 END;
25 -- STATIC FUNCTION ODCIStatsFunctionCost (
26 -- func IN SYS.ODCIPredInfo,
27 -- cost OUT SYS.ODCICost,
28 -- args IN SYS.ODCIArgDescList,
29 -- i_col1 in NUMBER,
30 -- env IN SYS.ODCIEnv
31 -- ) RETURN NUMBER
32 -- IS
33 -- BEGIN
34 -- cost := sys.ODCICost(10000,5,0,0);
35 -- RETURN odciconst.success;
36 -- END;
37 END;
38 /
Type body created.
SQL> But this approach is not happy - perhaps not liking the function with no arguments?
SQL> disassociate statistics from functions f1;
Statistics disassociated.
SQL> ASSOCIATE STATISTICS WITH FUNCTIONS f1 USING test_stats_ot;
Statistics associated.
SQL> select count(*) from t1 where col1 >= f1;
select count(*) from t1 where col1 >= f1
ERROR at line 1:
ORA-00604: error occurred at recursive SQL level 1
ORA-06550: line 12, column 22:
PLS-00103: Encountered the symbol "ÀÄ" when expecting one of the following:
) , * & = - + < / > at in is mod remainder not rem =>
<an exponent (**)> <> or != or ~= >= <= <> and or like like2
like4 likec between || multiset member submultiset
SQL> So, back to F2 again (uncommenting argument i_col1 in ODCIStatsSelectivity):
SQL> disassociate statistics from functions f1;
Statistics disassociated.
SQL> disassociate statistics from functions f2;
Statistics disassociated.
SQL> ASSOCIATE STATISTICS WITH FUNCTIONS f2 USING test_stats_ot;
Statistics associated.
SQL> select count(*) from t1 where col1 >= f2(col1);
COUNT(*)
100000
SQL> select * from table(dbms_xplan.display_cursor);
PLAN_TABLE_OUTPUT
SQL_ID 2wxw32wadgc1v, child number 0
select count(*) from t1 where col1 >= f2(col1)
Plan hash value: 3724264953
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 139 (100)| |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL| T1 | 5000 | 25000 | 139 (62)| 00:00:01 |
Predicate Information (identified by operation id):
2 - filter("COL1">="F2"("COL1"))
19 rows selected.
SQL> Nothing obviously happening.
You'll note also in my interface type implementation that I commented out a declaration of ODCIStatsFunctionCost.
This post is probably already too long already so I've skipped some of the detail.
But when ODCIStatsFunctionCost was used with function F2, I presume I've made a mistake in the implementation because I had an error in the 10053 trace as follows:
Calling user-defined function cost function...
predicate: "RIMS"."F2"("T1"."COL1")
declare
cost sys.ODCICost := sys.ODCICost(NULL, NULL, NULL, NULL);
arg0 NUMBER := null;
begin
:1 := "RIMS"."TEST_STATS_OT".ODCIStatsFunctionCost(
sys.ODCIFuncInfo('RIMS',
'F2',
NULL,
1),
cost,
sys.ODCIARGDESCLIST(sys.ODCIARGDESC(2, 'T1', 'RIMS', '"COL1"', NULL, NULL, NULL))
, arg0,
sys.ODCIENV(:5,:6,:7,:8));
if cost.CPUCost IS NULL then
:2 := -1.0;
else
:2 := cost.CPUCost;
end if;
if cost.IOCost IS NULL then
:3 := -1.0;
else
:3 := cost.IOCost;
end if;
if cost.NetworkCost IS NULL then
:4 := -1.0;
else
:4 := cost.NetworkCost;
end if;
exception
when others then
raise;
end;
ODCIEnv Bind :5 Value 0
ODCIEnv Bind :6 Value 0
ODCIEnv Bind :7 Value 0
ODCIEnv Bind :8 Value 4
ORA-6550 received when calling RIMS.TEST_STATS_OT.ODCIStatsFunctionCost -- method ignoredThere was never any such feedback about ODCIStatsSelectivity.
So, in summary, more questions than answers.
I'll try to have another look later. -
I want the list sql queries performed someone in one session based
V$SESSION V$SQLTEXT and audsid (taken from sys_context('USERENV','SESSIONID') ) are great .. session_id be generated by a trigger when the application logs on) but then uploading the list of sql queries made by that user (application) until they log off seems impossible.
I've tried creating triggers that check if V$SESSION changes with respect to an audsid number and sql_hash_value but it didn't work. I'm trying to work out why.
In the meantime I thought I'd post this to see if anyone else foudn another way.
I don't want to use sql trace that just gives load of info, I just want simple sql queries.
Auditting seemed a bit complicated, can that list ALL DML and DDL commands made by a user? if so how?
thanks
Bobbyquite right.
Oracle enterprise dedicated server 9.2.0.8 on solaris 10.
I just want to log all command DML and DDL, without stats or anything like that, simply a list, in a chronological order would be nice.
I found something called dbms_fga package but not sure if thats what I want. Seems I have to implement it on specific tables. which is not good if the application hasn't created the tables yet.
Thanks in advance. -
Help with SQL queries following migration
Hi there,
I have just migrated from MS SQL Server database to Oracle 10g database using the Oracle SQL Developer.
My application is using JDBC to access the database, and there are heaps of SQL statements that need to be verified and tested. I've found a number of SQL compatibility issues from my testing of the Oracle database and I hope you can help me the following.
1. Case sensitivity
Is it possible to not enforce case sensitivity (by default) when performing a select query?
If this is not possible, all the SQL statements will need to be changed to evaluate column based on uppercase.
2. Trailing white space
Is it possible to not evaluate trailing white space (by default) when performing a select query?
For example, suppose a table column studentNo has trailing spaces (after database migration), e.g. 'A182D '
when performing query - select * from student where studentNo = 'A182D'
no results can be found
3. Issue with Where condition containing with '' = ''
There are quite a number of SQL statements with Where condition containing '' = ''.
For example, the following SQL query doesn't return any results even though there are matching suburb that starts with 'ST'. These types of queries are mostly used in dynamic generated queries.
select * from Address where (suburb like 'ST%') and ('' = '' or country = '')
Any help or advice will be greatly appreciated.
Regards,
Jason GordonAs justin mentioned setting those NLS parameters will make oracle not to use your regular index. for that you must create a function based index. See example below.
SQL> create index t_idx on t (name)
2 /
Index created.
SQL> exec dbms_stats.gather_table_stats(user,'T',cascade=>true)
PL/SQL procedure successfully completed.
SQL> explain plan for
2 select * from t where name = 'karthick'
3 /
Explained.
SQL> select * from table(dbms_xplan.display)
2 /
PLAN_TABLE_OUTPUT
Plan hash value: 2946670127
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 9 | 1 (0)| 00:00:01 |
|* 1 | INDEX RANGE SCAN| T_IDX | 1 | 9 | 1 (0)| 00:00:01 |
Predicate Information (identified by operation id):
PLAN_TABLE_OUTPUT
1 - access("NAME"='karthick')
13 rows selected.
SQL> delete from plan_table
2 /
2 rows deleted.
SQL> alter session set NLS_COMP=ANSI;
Session altered.
SQL> alter session set NLS_SORT=BINARY_CI;
Session altered.
SQL> explain plan for
2 select * from t where name = 'karthick'
3 /
Explained.
SQL> select * from table(dbms_xplan.display)
2 /
PLAN_TABLE_OUTPUT
Plan hash value: 1601196873
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 9 | 5 (0)| 00:00:01 |
|* 1 | TABLE ACCESS FULL| T | 1 | 9 | 5 (0)| 00:00:01 |
Predicate Information (identified by operation id):
PLAN_TABLE_OUTPUT
1 - filter(NLSSORT("NAME",'nls_sort=''BINARY_CI''')=HEXTORAW('6B61727
46869636B00') )
14 rows selected.
SQL> create index t_idx_1 on t(NLSSORT(name,'NLS_SORT=BINARY_CI'))
2 /
Index created.
SQL> exec dbms_stats.gather_table_stats(user,'T',cascade=>true)
PL/SQL procedure successfully completed.
SQL> /
create index t_idx_1 on t(NLSSORT(name,'NLS_SORT=BINARY_CI'))
ERROR at line 1:
ORA-00955: name is already used by an existing object
SQL> delete from plan_table
2 /
2 rows deleted.
SQL> explain plan for
2 select * from t where name = 'karthick'
3 /
Explained.
SQL> select * from table(dbms_xplan.display)
2 /
PLAN_TABLE_OUTPUT
Plan hash value: 2580036035
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 3 | 27 | 2 (0)| 00:00:01 |
| 1 | TABLE ACCESS BY INDEX ROWID| T | 3 | 27 | 2 (0)| 00:00:01 |
|* 2 | INDEX RANGE SCAN | T_IDX_1 | 3 | | 1 (0)| 00:00:01 |
Predicate Information (identified by operation id):
2 - access(NLSSORT("NAME",'nls_sort=''BINARY_CI''')=HEXTORAW('6B6172746869636B00') )Thanks,
Karthick. -
SQL Queries, filter with multiple radio Buttons
I am trying to figure out how to filter my datagridview with SQL queries so that both of them have to be met for data to show up not just one.
My datagridview is bound to an Access Database.
I basically would want it filtered by 'Width' and 'Wood Type'
I have radio buttons in group boxes so a width and wood can be selected. However only one Query is applied at a time.Public Class Form1
Private Sub StickersBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
Me.Validate()
Me.StickersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.TestDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'TestDataSet.Stickers' table. You can move, or remove it, as needed.
Me.StickersTableAdapter.Fill(Me.TestDataSet.Stickers)
AcceptButton = Button1
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
Try
Me.StickersTableAdapter.Wood_Oak(Me.TestDataSet.Stickers)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub RadioButton2_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton2.CheckedChanged
Try
Me.StickersTableAdapter.Wood_Walnut(Me.TestDataSet.Stickers)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub RadioButton3_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton3.CheckedChanged
Try
Me.StickersTableAdapter.Width14(Me.TestDataSet.Stickers)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub RadioButton4_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton4.CheckedChanged
Try
Me.StickersTableAdapter.Width18(Me.TestDataSet.Stickers)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If RadioButton5.Checked = True Then
If TextBox1.Text = "" Then
Else
Me.StickersBindingSource.Filter = "Width LIKE '" & TextBox1.Text & "%'"
DataGridView1.Refresh()
End If
ElseIf RadioButton6.Checked = True Then
If TextBox1.Text = "" Then
Else
Me.StickersBindingSource.Filter = "[Wood Type] LIKE '" & TextBox1.Text & "%'"
DataGridView1.Refresh()
End If
ElseIf RadioButton5.Checked = False And RadioButton6.Checked = False Then
MsgBox("Please Select a Search Criteria")
End If
End Sub
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
Try
Me.StickersTableAdapter.SearchWood(Me.TestDataSet.Stickers)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
End Class -
Generate ER Diagram with Sql Queries ?
Hi Expertie,
I am new to Oracle Sql Developer Data Modeler.
I am having doubt in Oracle Sql Developer Data Modeler. Can we create ER Diagram with sql queries ?
Ex: select Ename, EAge, Eemail, ESalary, DDept, Dname, Estatus from Emp E join Dept D on E.EmpId = D.Empid
Where EAge in (20, 25, 30, 35)
Please provide me the answer and suggestion. It will be greatful for me.
Thanks & Regards
BhaskarYes, you can engineer your physical model to a logical one, then you'll have an ERD as well. It's a right-click on the model I believe.
To be more specific, if you relational model is loaded, you can use the button in the toolbar that looks like a double-blue-arrow, or you can mouse-right-click on your relational model in the tree. This will engineer your model to a logical one. You'll then have your ERD.
Edited by: Jeff Smith SQLDev PM on Apr 29, 2013 9:53 AM -
Erratic Report Region Behavior with Dynamic SQL Queries
I'm running HTMLDB v 1.5.1.00.12 and I've noticed some odd behavior with report regions using dynamic SQL queries. Every so often, our testers will run a page containing a dynamic sql report region and get the following error, (despite the fact the query was working only moments ago and no other developer has touched it):
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
or sometimes
failed to parse SQL query:ORA-01403: no data found
The only solution I've found so far is to:
1) Make a copy of the failed report region.
2) Disable or delete the original failed report region.
The new copy of the report region runs without issue.
My search of the forums turned up the following two threads, but neither provided me with a clear explanation of the cause, and how to avoid it:
ORA-06502:PL/SQL: numeric or value error: character string buffer too small
Re: Import Export Error (ORA-06502)
The columns being returned are below the 4000 character limit, and the rows being returned are far less than 32k in size.
Could this have anything to do with the way HTMLDB is internally storing the PL/SQL used to generate the dynamic SQL Query? Is there any known issue related to this with that version of HTMLDB?
This problem occurs without any discernable pattern or consistency, making it hard to determine where I should focus my efforts in tracking down the cause.Hi all,
My report seems to be behaving correctly once i set it to "Use Generic Column Names (parse query at runtime only)" :)
Cheers,
Joel -
How to replace one variable with another in large number of queries
Hello guys!
I have this situation: our company needs to use one variable instead of another for certain amount of queries.
Is there some way to automatically replace one variable with another for a certain characteristic in big number of queries ( like 150 - 200 ) ? Doing this manually would take lots of time)
Apreciate your help!you could try (at your own risk) the following:
1. search the technical id (ELTUID) of your variable in table RSZELTDIR
2. see where this variable is used in table RSZELTXREF (by filling RSZELTDIR-ELTUIID in RSZELTXREF-TELTUID)
3. add similar entries for your new variable
4. delete the entries for the old variable (they're part of the key, so you can't simply "change" them) -
I'm trying to change my ICloud e-mail to match the one associated with the Apple ID? Can someone tell me how to do this? Seems like the phone won't accept the new one, the message states "you already have acct associated....." (a given!!) I need help !!
You made a purchase and exhausted the credit on your card before it processed. All purchases are final. Contact iTunes Store support. You need to settle up before you can purchase or download anything else.
-
Pl/sql statement with output in reports
Hello,
I am quite new to reports and pl/sql, i have built a pl/sql statement with some loops that works fine when running it in sqlplus.
I would really like to have this running in reports with the variables (v_year, v_month and v_sumvalue) in a table/record in the data view, so i can use them just like any ordinary fields in a table for example in a diagram.
I have tried to create a package spec, setting up a record with the variables as fields. And then a pl/sql function with the following sql (which was a bit modified to work in the pl/sql function). Everything seemed to work since the pl/sql table/record was there with the variables as fields in it, but it never returned anything... just fatal error.
Here is the original pl/sql statement which is working in sqlplus, any help/directions in how to get this working so i can use the variables like fileds in a regular table would be fantastic:
DECLARE
v_year number(4);
v_month number(2);
v_sumvalue number(9,3);
v_sta varchar2(10);
v_end varchar2(10);
v_stopmonth number(2);
BEGIN
--## Get last 5 years ##--
select
to_char(add_months(sysdate,-60),'YYYY'),
to_char(sysdate,'MM')
into v_year, v_stopmonth
from
dual;
--dbms_output.put_line(v_year);
--## Loop 5 years ##--
for i in 1..5 loop
v_year := v_year + 1;
--dbms_output.put_line(v_year);
--## Loop 12 times (months) ##--
for k in 0..11 loop
v_month := k +1;
--dbms_output.put_line(v_year ||'-'|| v_month);
select
sum(nvl(p.value,0)) / 3,
last_day(add_months(to_date(v_year ||'-'|| v_month ||'-01','YYYY-MM-DD'),-3))+1,
last_day(to_date(v_year ||'-'|| v_month ||'-01','YYYY-MM-DD'))
into v_sumvalue, v_sta, v_end
from
project p
where
p.country_code = 'SWE'
and
p.project_type_code = 'P'
and
p.start_date between last_day(add_months(to_date(v_year ||'-'|| v_month ||'-01','YYYY-MM-DD'),-3))+1 and last_day(to_date(v_year ||'-'|| v_month ||'-01','YYYY-MM-DD'))
and
p.q_category_code between 1000 and 1299
and
p.geography_code between 2100 and 2199;
dbms_output.put_line(v_year ||'-'|| v_month ||' '|| v_sumvalue);
--dbms_output.put_line(v_year ||'-'|| v_month ||' '|| v_sumvalue ||' '|| v_sta ||' '|| v_end);
--## Stop monthloop ##--
end loop;
--## Stop yearloop ##-
end loop;
END;Output:
2003-1 19.1
2003-2 20.1
2007-11 164.5
2007-12 135.167Best regards,
OlleHi,
Maybe pipelined functions will be useful for you:
http://www.oracle.com/technology/sample_code/tech/pl_sql/htdocs/x/Table_Functions_Cursor_Expressions/Pipelined_Table_Functions.htm
Regards
Jakub Flejmer -
Dynamic SQL Statement with table name
Dear all
i like to have a SQL statement with a dynamic tablename. Is this possible? If yes, how?
should be something like "select * from <mytablename>"
Thank you
HerbertYes this is possible. use the below reference code for this.
data: g_tablename type w_tabname,
gv_dref TYPE REF TO data.
FIELD-SYMBOLS: <g_itab> TYPE STANDARD TABLE.
gv_tabname = p_tablename (take table name form selection screen or as per ur requirement)
CREATE DATA gv_dref TYPE TABLE OF (g_tabname).
ASSIGN gv_dref->* TO <g_itab>.
now use the below select query to fetch the data
SELECT * FROM (gv_tabname) INTO TABLE <g_itab>.
Hope this will help
Maybe you are looking for
-
HT201471 i message not working ?
i tried to activate the i message service on my ipad mini but i get message to inform me the user name or password incorrect ? but i am sure is correct!
-
Since updating last time Firefox will not open new tabs unless I right click on a link. It won't open them via file or the tab at the top of the brwoser or usinf ctrl + t. Anyone know how to fix this?
-
I have a motion menu with audio - I want to click a button and have a different audio play - seems simple but I can't get anything to work - can anyone help? Thanks
-
Error in Client import Post Processing
Hi after importing a client with SAP_ALL profile when i am running SCC7 i m getting following Error Runtime Error DBIF_RSQL_SQL_ERROR Except CY_SY_OPEN_SQL_DB Sql error in the database when accessiong a table Missing RAISING Clause in Inter
-
Converting an image as a blob content from .gif format to .jpg format
Hi Does anyone know how to convert a blob content from .gif format to .jpg format? I've tried looking at the process-method of intermedia, but I can't figure out how it's supposed to work... I'm on a 10.2.0.2 standard edition database I simply have a