Pattern matching in sql scripts
Hi All,
I am trying to run some queries for database maintainence and to find out the number of rows inserted in a table on a day. These queries would be stored in a .sql file and a scheduler will trigger these files are regular intervals.
Amongst these queries , one query that we generally exceute in sql command line is:
select component, count(*) from test where timestamp like '%2010-11-30%' group by component order by count(*) desc;
This query gives me a list of components and the number of rows they inserted in 'test' table on a particular day. To fetch the data inserted on a particular day we manually give current date inside pattern matching string -> e.g where timestamp like '%2010-11-30%'
How can I use pattern matching (as in the above query) in my sql script. How can I fetch the current date and use it in the above sql for pattern matching.
Please help.
Assuming your timestamp column has a proper data type like DATE or TIMESTAMP then you should compare dates with dates or timestamps with timestamps. Not timesatamp with a string.
example
select component, count(*) cnt
from test
where timestamp>= trunc(sysdate)
and timestamp < trunc(sysdate) /* this line is only needed if you have timestamps in the future */
group by component
order by cnt desc;If your column is of the datatype timestamp then use SYSTIMESTAMP instead of SYSDATE.
Similar Messages
-
Help needed with pattern matching (analytics SQL ?)
Hello Forum Users,
I've got a curious problem on my hands that I am unable to think of an efficient way to code in Oracle SQL ....
(1) Background
Two tables :
MEASUREMENTS
ID NUMBER
M1 NUMBER
M2 NUMBER
M3 NUMBER
M4 NUMBER
INTERESTING_VALUES
ID NUMBER
M1 NUMBER
M2 NUMBER
M3 NUMBER
M4 NUMBER
(2) OUTPUT NEEDED
For each row in "MEASUREMENTS", count the number of matches in "INTERESTING_VALUES" (all rows). Please note that the matches might not be in the same column.... e.g. for a given row MEASUREMENTS M1 might match INTERESTING_VALUES M3.
I need to count 2,3 and 4 matches and provide the count values seperatley.
I am not interested in fuzzy matching (e.g. "greater than" or "less than"), the numbers only need to match exactly.
(You can use features up to 11g).
Thank you for your help.yup here you go...
SQL> select * from measurement;
ID M1 M2 M3 M4
1 30 40 110 120
2 12 24 175 192
3 22 35 147 181
SQL> select * from interesting;
ID M1 M2 M3 M4
1 16 171 30 110
2 40 171 30 110
5 181 147 35 22
4 175 12 192 24
3 175 86 192 24
SQL> SELECT id,
2 SUM(
3 CASE
4 WHEN LEN=1
5 THEN 1
6 ELSE 0
7 END) repeat2,
8 SUM(
9 CASE
10 WHEN LEN=2
11 THEN 1
12 ELSE 0
13 END) repeat3,
14 SUM(
15 CASE
16 WHEN LEN=3
17 THEN 1
18 ELSE 0
19 END) repeat4
20 FROM
21 (SELECT id,
22 spath ,
23 (LENGTH(spath)-LENGTH(REPLACE(LOWER(spath),',') ))/ LENGTH(',') LEN
24 FROM
25 (SELECT t.* ,
26 ltrim(sys_connect_by_path(cvalue,','),',') spath
27 FROM
28 (SELECT p.*,
29 row_number() over (partition BY id, id1 order by cvalue) rnum
30 FROM
31 (SELECT m.id,
32 m.m1 ,
33 m.m2 ,
34 m.m3 ,
35 m.m4 ,
36 (SELECT COUNT(*)
37 FROM interesting q
38 WHERE q.id=I.id
39 AND (q.m1 = column_value
40 OR q.m2 =column_value
41 OR q.m3 =column_value
42 OR m4 =column_value)
43 ) cnt ,
44 column_value cvalue,
45 i.id id1 ,
46 i.m1 m11 ,
47 i.m2 m21 ,
48 i.m3 m31 ,
49 i.m4 m41
50 FROM measurement m ,
51 TABLE(sys.odcinumberlist(m1,m2,m3,m4)),
52 interesting I
53 ORDER BY id,
54 id1 ,
55 cvalue
56 ) p
57 WHERE cnt=1
58 ) t
59 WHERE level >1
60 CONNECT BY prior id=id
61 AND prior id1 =id1
62 AND prior rnum <=rnum-1
63 --start with rnum=1
64 ORDER BY id,
65 id1 ,
66 cvalue
67 )
68 ORDER BY 1,2
69 )
70 GROUP BY id
71 ORDER BY 1;
ID REPEAT2 REPEAT3 REPEAT4
1 4 1 0
2 9 5 1
3 6 4 1I am posting the code without number formatting so that it gets easier for you to copy the code...
select id,sum(case when len=1 then 1 else 0 end) repeat2,sum(case when len=2 then 1 else 0 end) repeat3,sum(case when len=3 then 1 else 0 end) repeat4 from
(select id,spath,(LENGTH(spath)-LENGTH(REPLACE(LOWER(spath),',') ))/ LENGTH(',') len from
(select t.*
,ltrim(sys_connect_by_path(cvalue,','),',') spath
from (select p.*,row_number() over (partition by id, id1 order by cvalue) rnum from (SELECT m.id,
m.m1 ,
m.m2 ,
m.m3 ,
m.m4 ,
(SELECT COUNT(*)
FROM interesting q
WHERE q.id=I.id
AND (q.m1 = column_value
OR q.m2 =column_value
OR q.m3 =column_value
OR m4 =column_value)
) cnt ,
column_value cvalue,
i.id id1 ,
i.m1 m11 ,
i.m2 m21 ,
i.m3 m31 ,
i.m4 m41
FROM measurement m ,
TABLE(sys.odcinumberlist(m1,m2,m3,m4)),
interesting I
order by id,id1,cvalue
) p where cnt=1
) t where level>1
connect by prior id=id and prior id1=id1 and prior rnum<=rnum-1
order by id,id1,cvalue) order by 1,2) group by id order by 1Ravi Kumar
Edited by: ravikumar.sv on Sep 15, 2009 3:54 PM -
Hi experts,
I have a requirement for which I need to write a SQL. On our orders search screen there are 2 prompts.
1) Dealer name (Table.column - DLR_NAM)
2) State name (Table.column - STATE_NAM)
When user wants to find the orders placed by all dealers whose name starts with 'A' and state name with 'B', then our query is something like this
SELECT ORDER_ID, ORDER_ITEM, ORDER_QTY, ORDER_VALU
FROM ORDERS
WHERE DLR_NAM LIKE 'A%'
AND STATE_NAM LIKE 'B%'; -- A and B entered by user in the respective prompt text box
But there are countries like Greece for which states doesn't exists. In that case STATE_NAME is NULL and the above query becomes something like the below and doesn't return right results
SELECT ORDER_ID, ORDER_ITEM, ORDER_QTY, ORDER_VALU
FROM ORDERS
WHERE DLR_NAM LIKE 'A%'
AND STATE_NAM LIKE '%'; -- Pattern matching goes wrong due to this AND clause.
Please suggest how to fix this. It appears simple and my brain is not working after non-stop working for several days.You are saying that the user types something in both variables.
And then this query:
SELECT ORDER_ID, ORDER_ITEM, ORDER_QTY, ORDER_VALU
FROM ORDERS
WHERE DLR_NAM LIKE :bind_dealer || '%'
AND ( (:bind_state IS NULL) OR (:bind_state IS NOT NULL AND STATE_NAM LIKE :bind_state || '%') );returns rows with STATE_NAM null.
That does not make sense. If the users types in both variables, then the bindvariable :bind_state is not null, and then STATE_NAM has to begin with the value of :bind_state.
The only thing I can think of is if you are binding wrong? What is your application coded in? C#? Java? ASP? .NET? How do you prepare your SQL query from your user inputs?
You will have to post a test case. Create table, insert some test data, run the sql and show it returns the wrong result. I cannot think of any problem without knowing more details :-) -
How to batch create SSO accounts from Windows or a PL/SQL script
We have just converted our 6i Forms and Reports to 10g (10.1.2.0.2), and run them against a 9i database. In order to be able to securely run reports we set up and configured SSO for a few accounts via the Oracle Identity Management Provisioning Console. We do not have PORTAL – nor do we want it. However, now we need to create about 500 SSO accounts at once. We would prefer to be able to create these accounts in a batch method – eg run something from Windows command line or run a PL/SQL script. We have the DBMS_LDAP package successfully installed in that 9i database. Currently our list of 500 users is simply in a table in the 9i db.
Spent several hours looking through both this site and Metalink, but so far no luck – especially because we don’t have or want PORTAL. If anyone can help, would appreciate it very much.
ThanksUser dbms_ldap package in the database to use PL SQL to create your database
account and then an OID account with a RAD to match the database login. If you
You may have to load the DBMS_Ldap package from the database ADMIN directory first to be available in the database.
LDAP SQL Ex.
user_username := LOWER(new_user) || '@domain.com'; -
retval := dbms_ldap.search_s(my_session, ldap_base,
dbms_ldap.scope_subtree, 'uid=' || user_username, my_attrs, 0,
my_message);
retval := dbms_ldap.count_entries(my_session, my_message);
my_entry := dbms_ldap.first_entry(my_session,my_message);
my_dn := dbms_ldap.get_dn(my_session,my_entry);
dbpassword := 'PASSWD01';
isvalidrad := forms_rad.newraddefinition(radname,new_user,dbpassword,
dbtnsnames,errormessage);
sessionestablished := forms_rad.createoidsession(ldap_user, ldap_passwd,
ldap_host, ldap_port, ldap_base);
radcreated := forms_rad.createradforcn(my_dn, 'false', errormessage);
-- Create new user's database account same as RAD account.
v_sql := 'CREATE USER "' || new_user || '" IDENTIFIED BY ' || dbpassword ||
' DEFAULT TABLESPACE JLIM TEMPORARY TABLESPACE TEMP';
EXECUTE IMMEDIATE v_sql;
v_sql := 'GRANT CONNECT TO ' || new_user;
EXECUTE IMMEDIATE v_sql; -
Pattern matching using Regular expression
Hi,
I am working on pattern matching using regular expression. I the table, I have 2 columns A and B
A has value 'A499BPAU4A32A386KBCZ4C13C41D20E'
B has value like '*CZ4*M11*7NQ+RDR+RSM-R9A-R9B'
the requirement is that I have to match the columns of B in A. If there is a value with * sign, this must be present in A like 'CZ4' should exit in string A.
The issue I am facing is that there are 2 values with * sign. The code works fine for first match (CZ4) but it does not look further as M11 does not exist in A.
I used the condition
AND instr(A,substr(REGEXP_SUBSTR(B, '*[^*]{3}'),2) ,1)=0
First of all, is this possible to match multiple patterns in one condition?
If yes, please suggest.
Thanksuser2544469 wrote:
Thanks a lot Frank. This query worked wonderful for the test data I have provided however I have some concerns:
- query doesnot include the column BOOK which is a mandatory check.Sorry, that was my mistake. It was a very easy mistake to make, since you posted sample data where it didn't matter. Instead of doing a cross-join between vn and got_must_have_cnt, do an inner join, using book. That means book will have to be in got_must_have_cnt, and all the sub-queries from which it descends. Look for comments that say "March 22".
If you want to treat '+' in test_cat.codes as '*', then the simplest thing is probably just to use REPLACE, so that when the table has '+', you use '*' instead.
WITH got_token_cnt AS
SELECT cat
, book -- Added March 22
, REPLACE (codes, '+', '*') AS codes -- If desired. Changed March 22
, LENGTH (codes) - LENGTH ( TRANSLATE ( codes
, 'x*+-'
, 'x'
) AS token_cnt
FROM test_cat
, cntr AS
SELECT LEVEL AS n
FROM ( SELECT MAX (token_cnt) AS max_token_cnt
FROM got_token_cnt
CONNECT BY LEVEL <= max_token_cnt
, got_tokens AS
SELECT t.cat
, t.book -- Added March 22
, REGEXP_SUBSTR ( t.codes
, '[*+-]'
, 1
, c.n
) AS token_type
, SUBSTR ( REGEXP_SUBSTR ( t.codes
, '[*+-][^*+-]*'
, 1
, c.n
, 2
) AS token
FROM got_token_cnt t
JOIN cntr c ON c.n <= t.token_cnt
, got_must_have_cnt AS
SELECT cat, book -- Changed March 22
, COUNT (CASE WHEN token_type = '*' THEN 1 END) AS must_have_cnt
FROM got_tokens
GROUP BY cat, book -- Changed March 22
SELECT mh.cat
, vn.vn_no
FROM got_must_have_cnt mh
JOIN vn ON mh.book = vn.book -- Changed March 22
LEFT OUTER JOIN got_tokens gt ON mh.cat = gt.cat
AND INSTR (vn.codes, gt.token) > 1
GROUP BY mh.cat
, mh.must_have_cnt
, vn.vn_no
HAVING COUNT (CASE WHEN gt.token_type = '*' THEN 1 END) = mh.must_have_cnt
AND COUNT (CASE WHEN gt.token_type = '-' THEN 1 END) = 0
ORDER BY mh.cat
- query is very slow with 60000 records in vn table. Cost is somewhere around 36000.See these threads:
When your query takes too long ...
HOW TO: Post a SQL statement tuning request - template posting
Relational databases were designed to have (at most) one piece of information in each column. If you decide to have multiple items in the same column (as you have a variable number of tokens in the codes column), don't be surprised if that makes things slower and more complicated. Most of the query I posted, and perhaps most of the time needed, is jsut to normalize the data. If you stored the data in a narmalized form, perhaps something like got_tokens, then you wouldn't need the first 3 sub-queries that I posted.
Edited by: Frank Kulash on Mar 22, 2011 12:04 PM -
Now I met a difficult question.Firstly,we have a criterion table as below:Combination Name Service UnitLength UnitHeight LoadStatus Bill No ......(until unbounded fields). Some data like this
Combination Name | Service | UnitLength | UnitHeight | LoadStatus | Bill No ......
COM1 | CSC | 40 | 96 |
COM2 | CSC | 40 | 96 | F |
COM3 | CSC | 40 | 96 | F | SEA-SCS
If there is an object has the attribute UnitLength equal 40 and UnitHeight equal 96 the correct combination COM1 is selected;otherwise, if
it has the attribute UnitLength equal 40 and UnitHeight equal 96 and LoadStatus equal F then the appropriate combination COM2 is selected; then if the object has UnitLength equal 40 and UnitHeight equal 96 and LoadStatus equal F and many other conditions ,the featest pattern match will be the completely match combination.But when there is no completely match combination,we may get a combination closer match the object.For example,an object has the following attributes UnitLength equal 40 and UnitHeight equal 96 and LoadStatus equal F Bill No equal SEA-SCS* ,the best result will be COM3.
How can we find a pl/sql procedure resolve this question?
Thanks very much! Look forward to your answer!
About the combination structure(Combinaton.xsd) as below:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xdb="http://xmlns.oracle.com/xdb" version="1.0" xdb:storeVarrayAsTable="true">
<xs:element name="()" type="CombinationType" xdb:defaultTable="COMBINATION"/>
<xs:complexType name="CombinationType" xdb:SQLType="Combination_T">
<xs:sequence>
<xs:element name="FilterNam" type="FilterNamType" xdb:SQLName="FilterNam"/>
<xs:element name="Priority" type="PriorityType" xdb:SQLName="Priority"/>
<xs:element name="FilterType" type="FilterType" minOccurs="0" xdb:SQLName="TYPE"/>
<xs:element name="Service" type="ServiceType" xdb:SQLName="Service"/>
<xs:element name="Operator" type="OperatorType" xdb:SQLName="Operator"/>
<xs:element name="OperTim" type="OperTimType" xdb:SQLName="OperTim"/>
<xs:element name="FilterItems" type="FilterItemsType" xdb:SQLName="FilterItems"/>
<xs:element name="PlanMatrix" type="PlanMatrixType" xdb:SQLName="PlanMatrix"/>
<xs:element name="Discription" type="DiscriptionType" xdb:SQLName="Discription"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="FilterItemsType" xdb:SQLType="FilterItems_T">
<xs:sequence>
<xs:element name="FilterItem" type="FilterItemType" maxOccurs="unbounded" xdb:SQLName="FilterItem" xdb:SQLCollType="FilterItem_V"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="FilterItemType" xdb:SQLType="FilterItem_T">
<xs:sequence>
<xs:element name="Charateristic" type="CharateristicType" xdb:SQLName="Charateristic"/>
<xs:element name="Oper" type="OperType" xdb:SQLName="Oper"/>
<xs:element name="Value" type="ValueType" xdb:SQLName="Value"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="PlanMatrixType" xdb:SQLType="PlanMatrix_T">
<xs:sequence>
<xs:element name="PlanMatrixElement" type="PlanMatrixElementType" maxOccurs="3" xdb:SQLName="PlanMatrixElement" xdb:SQLCollType="PlanMatrixElement_V"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="PlanMatrixElementType" xdb:SQLType="PlanMatrixElementTypem_T">
<xs:sequence>
<xs:element name="Interval" type="IntervalType" xdb:SQLName="Interval"/>
<xs:element name="DaysBfETD" type="DaysBfETDType" xdb:SQLName="DaysBfETD"/>
<xs:element name="Resevevation" type="ResevevationType" xdb:SQLName="Resevevation"/>
<xs:element name="Algorithm" type="AlgorithmType" xdb:SQLName="Algorithm"/>
<xs:element name="HDP" type="HDPType" xdb:SQLName="HDP"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="FilterNamType">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="30"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="OperatorType">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="10"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ServiceType">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="20"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="FilterType">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="4"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="PriorityType">
<xs:restriction base="xs:integer"/>
</xs:simpleType>
<xs:simpleType name="OperTimType">
<xs:restriction base="xs:date"/>
</xs:simpleType>
<xs:simpleType name="CharateristicType">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="35"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="OperType">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="10"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ValueType">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="35"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="DiscriptionType">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="35"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="IntervalType">
<xs:restriction base="xs:integer"/>
</xs:simpleType>
<xs:simpleType name="DaysBfETDType">
<xs:restriction base="xs:integer"/>
</xs:simpleType>
<xs:simpleType name="ResevevationType">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="35"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="AlgorithmType">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:maxLength value="35"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="HDPType">
<xs:restriction base="xs:string">
<xs:minLength value="0"/>
<xs:maxLength value="35"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
And the data(Combination.xml) like that:
<Combination
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://localhost/xml_test//Combination.xsd">
<FilterNam>40/8.6/F/BILL</FilterNam>
<Priority>5</Priority>
<Service>KR-SHIPPING-LINE</Service>
<Operator>ZHANGRUI</Operator>
<OperTim>2010-06-09</OperTim>
<FilterItems>
<FilterItem>
<Charateristic>UnitLegth</Charateristic>
<Oper>=</Oper>
<Value>40</Value>
</FilterItem>
<FilterItem>
<Charateristic>UnitHeigh</Charateristic>
<Oper>=</Oper>
<Value>8.6</Value>
</FilterItem>
<FilterItem>
<Charateristic>LoadStatus</Charateristic>
<Oper>=</Oper>
<Value>F</Value>
</FilterItem>
<FilterItem>
<Charateristic>BillNo</Charateristic>
<Oper>=</Oper>
<Value>SEA-BILLING-NO.1</Value>
</FilterItem>
</FilterItems>
<PlanMatrix>
<PlanMatrixElement>
<Interval>1</Interval>
<DaysBfETD>3</DaysBfETD>
<Resevevation>1 BAY</Resevevation>
<Algorithm>MIX VESSEL</Algorithm>
</PlanMatrixElement>
</PlanMatrix>
</Combination>
Edited by: user10904897 on 2010-6-9 下午8:23
Edited by: user10904897 on 2010-6-9 下午8:57my best would be to do something like the following since i don't have oracle and can't simulate it right now:
select a.*,
case when unitlength = 40 and unitheight = 96 and loadstatus ='F' and billno = 'SEA-SCS' then 'COM3'
when unitlength = 40 and unitheight = 96 and loadstatus ='F' and billno != 'SEA-SCS' then 'COM2'
when unitlength = 40 and unitheight = 96 and loadstatus != 'F' then 'COM1'
else 'print what ever you want'
end
from <table_name>
where <any_conditions_you_want_if_any>
; -
Getting Log File Pattern Matched Line Count metric to work ?
Hi
has anyone been able to get this to work with more complex Perl expressions ?
Basically I can get simple, single expressions to match.
EG *(does not exist)* will match the text *"does not exist"* anywhere in a file.
However, if I want to match either does not exist OR file not found I should be able to do something like
*(does not exist)|(file not found)* OR *(does not exist|file not found)* but this just doesn't work.
I want to be able to do more complex expressions, using *\i* (ignore case), and *^* (start of line) *$* (end of line) expressions too.
I can test the matching functionality using a simple perl program, and I know the expression works in Perl.
Oracle is supposed to be using a perl pattern match but seems to fail unless it is a single simple expression.
Anyone been able to use this functionality at all.
Many thanks.I have a chance to look into the parse-log1.pl script which is responsible for monitoring the log files and generating the alerts for EMGC. I am just pasting the comments given in this file
# This script is used in EMD to parse log files for critical and
# warning patterns. The script holds the last line number searched
# for each file in a state file for each time the script is run. The
# next run of the script starts from the next line. The state file name
# is read from the environment variable $EM_STATE_FILE, which must
# be set for the script to run.
but in my case this is not happending according to log files it is storing the lst read line of the log file but it is not using that info in its next run. The file will be scanned from the begining again but this is not the case with emagent.log file monitoring its working fine as expected and explained in the script file.
According to my observation this is becasue of the script is rotating my log file for each run i dont know how stop it. I just want to scan my log file I dont want to rotate my log file for each run of the script. Could any one please help me to solve this problem
Thanks
Ashok Chava. -
IF statement syntax in SQL script view
I need to include a "IF" condition in the "SELECT" section of my SQL script view.
I tried the following syntax's but I get the error 'Incorrect SQL syntax near 'IF'
1. IF(Revenue <> '0' AND Quantity <> '0', Revenue/Quantity, '0') AS Gross Price
2. IF(Revenue != '0' AND Quantity != '0', Revenue/Quantity, '0') AS Gross Price
3. IF(Revenue <> '0' AND Quantity <> '0' THEN Revenue/Quantity ELSE '0' END) AS Gross Price
4. IF(Revenue != '0' AND Quantity != '0' THEN Revenue/Quantity ELSE '0' END) AS Gross Price
My final SQL would read like follows:
SELECT field1, field2, IF(......) AS field3
FROM table1
Can anybody please help with the correct IF statement syntax to be used in the SQL script based view?Hi Lakshmi,
below is the syntax for IF statement.
IF <bool_expr1> THEN
<then_stmts1>
ELSEIF <bool_expr2>
THEN <then_stmts2>
[ELSE <else_stmts3>]
END IF
eg :
BEGIN
DECLARE found INT := 1;
SELECT count(*) INTO found FROM books WHERE isbn = :v_isbn;
IF :found = 0 THEN
INSERT INTO books VALUES (:v_isbn, 'In-Memory Data Management', 1, 1, '2011', 42.75, 'EUR');
ELSE
UPDATE books SET price = 42.75 WHERE isbn =:v_isbn;
END IF;
END;
Sreehari -
IF Condition in a PL/SQL Script give a report error.
Hello, Im German and I hope you can unterstand my Question.
First, I work with the HTML DB Version 1.6.0.0.0.87 and the Oracle Version 9.2.0.6.
I create a SQL Report, where a PL/SQL Script return the SQL Statement for the Report. This is my source-code, I have short it...:
Declare
sql_str varchar(2000);
sql_str_select varchar(1000) :=' select dim_sparte ... ';
sql_str_from varchar(1000) := ' from faktentabelle,dim_sparte ';
sql_str_where varchar(1000):= ' where and faktentabelle.zeit_id = :POPUP_ZEIT ';
sql_str_groupby varchar(1000):= ' group by dim_sparte.name, faktentabelle.zeit_id ';
Begin
If ( (V('POPUP_NETZGEBIET') is not NULL) and (V('POPUP_NETZGEBIET') <>
'Alle Netzgebiete')) THEN
sql_str_select := sql_str_select || ' ,dim_organisationseinheit.netzgebiet_name ';
sql_str_from := sql_str_from || ' , dim_organisationseinheit ';
sql_str_where := sql_str_where || ' and faktentabelle ... and
dim_organisationseinheit.netzgebiet_name = :POPUP_NETZGEBIET';
sql_str_groupby := sql_str_groupby || ' , dim_orga .... ';
End IF;
sql_str:= sql_str_select || sql_str_from || sql_str_where || sql_str_groupby;
htp.print(sql_str);
Return sql_str;
End;
This Script include a IF-THEN condition. The Condition is true and the sql-String-Variables are updatet.
I can get the string with htp.print() and the Statement is OK.
The report get a Error report error: ORA-1403: no data found. If I copy the printet sql String in a new Report Region with SQL String, the Report is OK. When I write IF(true) instead of IF( Condition) the Report is OK, too.
I try ist with Varibalen V(name) and with :name. Its always the same problem. I cant use IF-THEN-Else Conditions in a Script.
Please help me and say me what is the problem???
Thanks,
SimonaHi Simona,
In the sql region below the region source see that you have " Use Generic Column Names (parse query at runtime only)" check and not " Use Query-Specific Column Names and Validate Query".
This error you usually get when you have a mismatch in your report heading.
Vivek
[email protected] -
Pl/sql script needed - Urgent
Hi All,
I have one problem. I have to populate a table having rows more than 500000000 $ through PL/SQL.
For getting the idea...I have created one dummy table " T1 " with column " X " having 9 rows and
values in source are -
row 1 = 10
row 5 = 20
row 8 = 30
Other rows(2, 3, 4, 6, 7, 9) are null.
I want to carry fwd the values so the values in the same table will come like -
row 1, 2, 3, 4 = 10
row 5, 6 ,7 = 20
row 8,9 = 30
For resolving the problem i have written a procedure :
DECLARE
CURSOR cur_adb IS SELECT * FROM t1 ;
var cur_adb%rowtype ;
var1 number(10) ;
BEGIN
OPEN cur_adb ;
LOOP
FETCH cur_adb INTO var ;
DBMS_OUTPUT.PUT_LINE ( 'x=') ;
EXIT WHEN cur_adb%ROWCOUNT > 10 ;
If var is not null
then update t1
set x = var ;
var1 := VAR;
else update t1
set x = var1 ;
exit;
end if;
END LOOP;
CLOSE cur_adb ;
END ;
But it is giving me wrong result as it is fetching more rows at a time.
Pls. send me the correct Pl/SQL script as soon as possible.
Note: You can directaly send the procedure to [email protected] .
Thanks & Regs,
AshishHello,
I got the solution by adding on more column in the source table :
source table : T1 -> x x_id
10 1
2
3
4
20 5
6
7
30 8
9
The procedure is :
SQL> DECLARE
2 CURSOR cur_adb IS SELECT x, x_id FROM t1 ;
3 var number(10) ;
4 var1 number(10) ;
5 var2 number(10) ;
6 BEGIN
7 OPEN cur_adb ;
8 LOOP
9 FETCH cur_adb INTO var , var2 ;
10 If var is not null
11 then var1 := VAR;
12 elsif var is null
13 then update t1
14 set x = var1
15 where x_id = var2;
16 end if;
17 DBMS_OUTPUT.PUT_LINE ('The value of x=' || var) ;
18 Exit when cur_adb%ROWCOUNT > 9 or cur_adb%NOTFOUND ;
19 END LOOP;
20 CLOSE cur_adb ;
21 END ;
22 /
The value of x=10
The value of x=10
The value of x=10
The value of x=10
The value of x=20
The value of x=20
The value of x=20
The value of x=30
The value of x=30
The value of x=30
PL/SQL procedure successfully completed.
Thanks everyone for helping me........
Regards,
Ashish -
Can't Upload SQL scripts or application scripts in APEX 3.1
I have installed APEX 3.1 on an Oracle 10g database.
I can log in to APEX, create applications, and run applications.
One application I import is the sample OEHR application which imports correctly at the hosted site.
However, when I try to upload an SQL script or import the sample application I get
"Page not Found" for this page http://csora:7777/pls/apex/wwv_flow.accept
I've included my dads.conf below and also some Apache error entries
Alias /i/ "e:\oracle\product\10.1.0\Db\Apache\Apache\images/"
AddType text/xml xbl
AddType text/x-component htc
<Location /pls/apex>
Order deny,allow
PlsqlDocumentPath docs
AllowOverride None
PlsqlDocumentProcedure wwv_flow_file_mgr.process_download
PlsqlDatabaseConnectString csora:1521:ORCL ServiceNameFormat
PlsqlNLSLanguage AMERICAN_AMERICA.AL32UTF8
PlsqlAuthenticationMode Basic
SetHandler pls_handler
PlsqlDocumentTablename wwv_flow_file_object$
PlsqlDatabaseUsername APEX_PUBLIC_USER
plsqlDefaultPage apex
PlsqlDatabasePassword hocking
Allow from all
</Location>
I:[Mon Apr 14 15:52:35 2008] [error] [client 10.116.101.158] [ecid: 1208202755:198.30.4.195:2696:2864:2873,0] File does not exist: e:/oracle/product/10.1.0/db/apache/apache/htdocs/pls/htmldb/builder/topnav2.gif
[Mon Apr 14 15:52:35 2008] [error] [client 10.116.101.158] [ecid: 1208202755:198.30.4.195:2696:2924:2771,0] File does not exist: e:/oracle/product/10.1.0/db/apache/apache/htdocs/pls/htmldb/builder/left_curve.gif
[Mon Apr 14 15:52:35 2008] [error] [client 10.116.101.158] [ecid: 1208202755:198.30.4.195:2696:2944:2767,0] File does not exist: e:/oracle/product/10.1.0/db/apache/apache/htdocs/pls/htmldb/builder/left_curve.gif
[Mon Apr 14 15:52:35 2008] [error] [client 10.116.101.158] [ecid: 1208202755:198.30.4.195:2696:2972:2750,0] File does not exist: e:/oracle/product/10.1.0/db/apache/apache/htdocs/pls/htmldb/builder/right_curve.gif
[Mon Apr 14 15:52:35 2008] [error] [client 10.116.101.158] [ecid: 1208202755:198.30.4.195:2696:2940:2762,0] File does not exist: e:/oracle/product/10.1.0/db/apache/apache/htdocs/pls/htmldb/builder/right_curve.gif
[Mon Apr 14 16:19:33 2008] [error] [client 10.116.101.158] [ecid: 1208204373:198.30.4.195:2696:2924:2773,0] File does not exist: e:/oracle/product/10.1.0/db/apache/apache/htdocs/pls/htmldb/builder/topnav2.gif
[Mon Apr 14 16:21:48 2008] [error] [client 10.116.101.158] [ecid: 1208204507:198.30.4.195:2696:2948:2801,0] mod_plsql: /pls/apex/wwv_flow.accept HTTP-404 ORA-00942: table or view does not exist
[Mon Apr 14 16:23:29 2008] [error] [client 10.116.101.158] [ecid: 1208204609:198.30.4.195:2696:2788:2760,0] mod_plsql: /pls/apex/wwv_flow.accept HTTP-404 ORA-00942: table or view does not exist
[Mon Apr 14 16:23:29 2008] [error] [client 10.116.101.158] [ecid: 1208204609:198.30.4.195:2696:2788:2761,0] mod_wchandshake: incorrect uri: name="p_t04" passed in.
[Mon Apr 14 16:23:29 2008] [error] [client 10.116.101.158] [ecid: 1208204609:198.30.4.195:2696:2788:2761,0] Invalid URI in request -data; name="p_t04"
Am I missing some files or directories from the 3.1 install? Any help would be appreciated since I think I'm close to having APEX fully functional.Val,
In this line:
PlsqlDocumentTablename wwv_flow_file_object$
...that needs to be wwv_flow_file_objects$
Scott -
How to test a simple PL SQL function from another PL SQL script
Hi,
I have created a function. Now i need to test that whether it is returning the correct values or not.
For that, i have written anothe pl sql script and trying to call this function. Im passing all the IN parameters in that function. I assume here that OUT parameters will provide me the result. Im trying to display the OUT parameter one by one to see my result.
I'm using toad as sql client here connected with oracle.
pl sql script:-
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE('$$$$$$$ VINOD KUMAR NAIR $$$$$$$');
FETCH_ORDER_PRODUCT_DATA(320171302, 1006, 6999,
ODNumber OUT VARCHAR2, Line_Number OUT VARCHAR2,
ServiceID OUT VARCHAR2, BilltoNumber OUT VARCHAR2,
AnnualPrice OUT NUMBER, CoverageCode OUT VARCHAR2)
DBMS_OUTPUT.PUT_LINE('HERE IS THE RESULT ' | ODNumber );
DBMS_OUTPUT.PUT_LINE('HERE IS THE RESULT ' | Line_Number );
DBMS_OUTPUT.PUT_LINE('HERE IS THE RESULT ' | ServiceID );
DBMS_OUTPUT.PUT_LINE('HERE IS THE RESULT ' | BilltoNumber );
DBMS_OUTPUT.PUT_LINE('HERE IS THE RESULT ' | AnnualPrice );
DBMS_OUTPUT.PUT_LINE('HERE IS THE RESULT ' | CoverageCode );
END;
Function:-
Program Name : SPOT_Order_Product_Data_For_CFS.sql
Description : Function to Validate parameters from CFS
By : Vinod Kumar
Date : 08/19/2011
Modification History
By When TAR Description
CREATE OR REPLACE FUNCTION FETCH_ORDER_PRODUCT_DATA(orderNumber IN VARCHAR2, customerNumber IN VARCHAR2,
productLine IN VARCHAR2, ODNumber OUT VARCHAR2,
Line_Number OUT VARCHAR2, ServiceID OUT VARCHAR2,
BilltoNumber OUT VARCHAR2, AnnualPrice OUT NUMBER,
CoverageCode OUT VARCHAR2)
RETURN VARCHAR2 IS
lv_err_msg VARCHAR2(100) := '';
lv_bucket_id VARCHAR2(14);
lv_bill_number VARCHAR2(30);
lv_anual_price NUMBER;
lv_coverage_code VARCHAR2(8);
lv_quote_num NUMBER(10) := NULL;
lv_line_num NUMBER(5) := 0;
lv_customer_number VARCHAR2(30) := customerNumber;
lv_product_id VARCHAR2(14) := productLine;
lv_count_quote NUMBER := 0;
lv_quote_status VARCHAR2(5);
lv_quote_version NUMBER(2):=0;
BEGIN
IF INSTR(orderNumber, '-') = 0 THEN
lv_quote_num := orderNumber;
ELSE
lv_quote_num := SPT_Delimiter(orderNumber, 1, '-');
lv_line_num := SPT_Delimiter(orderNumber, 2, '-');
END IF;
--Check status of the quote COM, APP
SELECT COUNT(*) INTO lv_count_quote FROM sot_order_header WHERE ORDER_NUMBER=lv_quote_num
AND ORDER_STATUS IN ('APP', 'COM') AND CUSTOMER_NUMBER = lv_customer_number;
IF lv_count_quote = 0 THEN
lv_err_msg := 'Invalid Order number';
RETURN lv_err_msg;
END IF;
-- Fetch the latest version on SPOT quote
SELECT MAX(VERSION_NUMBER) INTO lv_quote_version FROM SPT_QUOTE_HEADER WHERE QUOTE_NUMBER = lv_quote_num
AND CUSTOMER_NUMBER = lv_customer_number;
-- If quote is valid fetch the data in OUT parameters
IF lv_line_num = 0 THEN
BEGIN
SELECT a.CUSTOMER_BILLTO_NUMBER,
b.LINE_NUMBER, b.BUCKET_ID,
b.ANNUAL_REF_RATE_USD, b.COVERAGE_CODE
INTO lv_bill_number,lv_line_num,lv_bucket_id,lv_anual_price,lv_coverage_code
FROM SPT_QUOTE_HEADER a, SPT_QUOTE_LINE b
WHERE a.QUOTE_NUMBER = lv_quote_num
AND a.CUSTOMER_NUMBER = lv_customer_number
AND a.VERSION_NUMBER = lv_quote_version
AND a.QUOTE_NUMBER = b.QUOTE_NUMBER
AND a.VERSION_NUMBER = b.VERSION_NUMBER
AND b.PRODUCT_ID = lv_product_id;
ODNumber := lv_quote_num;
BilltoNumber := lv_bill_number;
Line_Number := lv_line_num;
ServiceID := lv_bucket_id;
AnnualPrice := lv_anual_price;
CoverageCode := lv_coverage_code;
RETURN '';
EXCEPTION WHEN OTHERS THEN
lv_err_msg := 'Multiple PIDs existing in the SPOT order, please provide the SPOT order + line number as input data';
RETURN lv_err_msg;
END;
ELSE
BEGIN
SELECT a.CUSTOMER_BILLTO_NUMBER,
b.BUCKET_ID, b.ANNUAL_REF_RATE_USD,
b.COVERAGE_CODE
INTO lv_bill_number,lv_bucket_id,lv_anual_price,lv_coverage_code
FROM SPT_QUOTE_HEADER a, SPT_QUOTE_LINE b
WHERE a.QUOTE_NUMBER = lv_quote_num
AND a.CUSTOMER_NUMBER = lv_customer_number
AND a.VERSION_NUMBER = lv_quote_version
AND a.QUOTE_NUMBER = b.QUOTE_NUMBER
AND a.VERSION_NUMBER = b.VERSION_NUMBER
AND b.PRODUCT_ID = lv_product_id
AND b.LINE_NUMBER = lv_line_num;
ODNumber := lv_quote_num;
BilltoNumber := lv_bill_number;
Line_Number := lv_line_num;
ServiceID := lv_bucket_id;
AnnualPrice := lv_anual_price;
CoverageCode := lv_coverage_code;
RETURN '';
EXCEPTION WHEN OTHERS THEN
lv_err_msg := 'Multiple SPOT lines exist with same parameter';
RETURN lv_err_msg;
END;
END IF;
EXCEPTION
WHEN OTHERS THEN
lv_err_msg := '@@@ EXCEPTION THROWN @@@ '|| SUBSTR(SQLERRM,1,120);
RETURN lv_err_msg ;
END;
Don't look at the function, it might have errors but my primary concern is how to test this function. Once I start doing its testing then only i can understand any bugs(if any).
My pl sql is not so good. Im still learning. I don't understand IN and OUT parameters are.
I just know that IN parameters r those whick we pass in to the function wen we call it and OUT parameters are those through which we get the result.
Thanks in advance
Vinod Kumar Nair20100511 wrote:
I wondered how I could test the output of the function from within TOAD?I usually create the following function in my developer schema:
create or replace function BoolToChar( b boolean ) return varchar2 is
begin
if b then
return( 'TRUE' );
else
return( 'FALSE' );
end if;
end;To test a function like yours, the following will do in SQL*Plus/TOAD/etc:
begin
DBMS_OUTPUT.put_line(
BoolToChar( XCCC_PO_APPROVALLIST_S1.does_cpa_exist(1017934) )
end;
I'm probably doing 101 things wrong here, but thought I'd ask anyway and risk being shouted at.Shout at? You reckon? I thought people risked being beaten with a lead pipe, or pelted with beer cans and stale pretzels - which makes being shouted at a really safe and viable alternative. {noformat};-){noformat} -
Hello! I'm a student and I'm currently making a project using pattern matching.
My patterns are from chick foot/feet.
I'm created multiple pattern matching VI's to detect all the feet because I find it difficult/impossible to match all the feet with a single pattern/template.
However, when using multiple pattern matching VI's some pattern matches detect the same foot, hence overlapping.
So how can I make the overlaping pattern matches to be counted as one?
Thank you in advanceThank you for replying Sir Zwired1.
I'm still a newbie in using LabVIEW so pardon me if I can't understand fully
The objective of my project is to detect all the feet through pattern matching and count the pattern matches made.
"Keep a 2D array of counts, initialized to zero and the same size as your array of possible locations, and increment the value every time you get a match. If multiple pattern matching attempts result in a match a given location in your count array might be "3" but all you care about is if the number is greater than zero."
I'm sorry, but how do you do this? BTW, I'm using vision assistant. -
How can I convert a mysql sql script to a oracle sql script
Hi,
We have a bunch of tables with data running on a mysql server.
This should now be moved to an oracle 9 db.
are there any tools to convert the import script of a mysql db
to a format of the sql script that work for oracle ?
Thanks
MichaelOracle has a tool called Migration Toolbench, which supports MySQL 3.22 and 3.23:
http://otn.oracle.com/tech/migration/workbench/content.html
On this same topic, I was wondering if anybody has tried migrating from PostgreSQL to Oracle 9i. The workbench doesn't seem to support it, and feeding a pg_dump file directly into SQL*Plus is not working. -
How to reference dynamic parameters in the PL/SQL script
The meaning of dynamic parameter is the position and name of parameters will be changed based on the data structure of a referenced text file reading by the concerned PL/SQL script. Anybody can post a sample code will be very appreciated.
The SQL and PL/SQL discussion forum is a good source for this kind of information.
The URL is:
PL/SQL
Maybe you are looking for
-
ICloud deleted all my contacts and photos. How can I get it back?
All my contacts and photos from my iPhone and from my ICloud webpage are gone. I have an ICloud backup from yesterday morning so i tried restoring, but my contacts disappeared again after a few seconds. It says that i have 1000 photos, but I can't se
-
Can't get movie to play on itunes!
I just purchased and downloaded the movie Money Ball on itunes. After it finished downloading it showed up under the movies tab, but when I click it it brings me to the menu for Money Ball (Where it says play movie, scenes extras, etc...) and will no
-
Is it possible to flip stage video playback horizontally on iOS?
I'm using stage video in an app to play back some video and it would be useful if I could offer users the option to flip the video along the horizontal axis. i.e. the equivalent of scaleX = -1 on a normal display object. The reason I want to do thi
-
I am trying to view Tiff file, but the problem that it is not clear view I mean it is very bad look, not like view it in another Tiff viewer. and also it is too big, I mean the width and hight. any way, this is my code:- public void ReadingTiffFile()
-
Experts, can anybody let me know how many G/L accounts are required to be created in CIN for excise. Many thanx