construct to be used in a for loop - for-loop

I have sample Data like:
Table empdata:
Name Desig Sal
-------------------------
john staff 26000
sen owner 50000
smith assistant 10000
i want to print each of the columns like
Current field value is : John
Current field value is : staff
Current field value is : 26000
Current field value is : sen
Current field value is : owner
Current field value is : 50000.. and so on
I am able to use cursor to fetch the emp data:
cursor c1 is
select name, desig, sal from empdata;
but i want to iterate over the columns too. I have shown 3 columns here, but there are atleast 30 columns in actual data, and i would like to print each of the field.
Please help.

Hi you can use this kind basic code.
begin
for i in (select * from emp where rownum < 5)
Loop
dbms_output.put_line('Current field value is: '||i.Emp_id);
dbms_output.put_line('Current field value is: '||i.emp_name);
end loop;
end;

If I understand you correctly, I think you're after something like:
select name,
desig,
sal,
(select approved from approval_table apv1 where apv1.data = emp.name) name_aprvd,
(select approved from approval_table apv2 where apv2.data = emp.desig) desig_aprvd,
(select approved from approval_table apv3 where apv3.data = emp.sal) sal_aprvd
from empdata emp;
Quite what you expect to do with the information once you've got it, I'm not sure. Maybe you return this as a cursor? Maybe you pass it into a procedure? I'm not sure, but hopefully you have enough information to sort out your requirement?

Related

How to execute an INSERT that's in a SELECT statement?

for my DB course i have a table: lab4Central which columns are: productid, description and plantid,
The plant QRO has and id = 1000, an example: 12799, 'Product 12799', 1000.
and the plant SLP has an id = 2000, ex: 29665, 'Product 29665', 2000.
I have to add new registers for other 2 plants: GDA and MTY.
For GDA the registers are the same of the plant QRO but it has tu adjust the productid + 20000, the same for MTY but with the registers of SLP so at the end it will look like:
Plant GDA: 329799, 'Product 32799', 3000.
plant MTY: 49665, 'Product 49665', 4000.
AS you can see for GDA the register is the same of the one in QRO but another plantid and we add 20000 to the productid, the same for MTY.
I code this which give me the correct values:
SELECT 'INSERT INTO LAB4CENTRAL VALUES('||(PRODUCTID+20000) || ',' || DESCRIPTION || ','|| 3000 ||');' FROM LAB4CENTRAL WHERE PLANTID=1000;
But it's just a select and i don't know how to execute the insert statement so it insert the data in the table.
hope you can help me.
What you want is actually the opposite of what you wrote. Instead an Insert... Select... is probably what you are after.
INSERT INTO LAB4CENTRAL
SELECT ProductID + 20000, 'Product' || Productid + 20000, 3000
FROM LAB4CENTRAL
WHERE PlantID = 1000;
That may need to be tweaked to fit your data, but the basic idea is to write a SELECT statement that gives you the result set that you then want to insert into the table.
assuming you want insert the select result in the column ProductId , Description and your_col_fro_3000
You could use a INSERT SELECT
INSERT INTO LAB4CENTRAL(ProductID, Description, your_col_for_3000)
SELECT ProductID + 20000, 'Product' || (Productid + 20000), 3000
FROM LAB4CENTRAL
WHERE PlantID = 1000;
It can very well be a trick to generate INSERT statements that then manually are executed, maybe in batches of circa 100 lines.
Otherwise one would do an INSERT ... SELECT statement. But that is not possible for the same table, hence this solution.
See also OUTPUT TO FILE or such (I do not know at this moment).

finding pattern data through sql query

How can I get particular pattern of data using sql query?
I have a string which has data like "Valid data: emp no - 123 emp age - 23 emp type - M."
So here I want whatever I have in emp age i.e. 23. The string format will be same. I don't want to get emp age based on position as it can change ,is there any other way to get emp age?
Is a query which will find emp age tag in the string and then look three places after that tag to get emp age value?
If the text is always the same you can try something like the following.
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(ColumnA, 'emp age - ', -1), ' ', 1) AS Age
FROM table;
Oracle has built-in regular expression functions. If, as you say, the format is always the same, extracting the second group of numbers will give you the outcome you desire:
SQL> select regexp_substr('Valid data: emp no - 123 emp age - 23 emp type - M.'
2 , '[0-9]+', 1, 2) as emp_age
3 from dual
4 /
EM
--
23
SQL>
These functions are covered in the documentation. Find out more.
Use the built-in Regular Expression functions.

ORA-01422: exact fetch returns more than requested number of rows pl/sql

I have this proc in my PL/SQL.
when i run it in sql dev, it is giving me exactly one row (one column)
PROCEDURE Newpo_code(sp_code OUT VARCHAR2)
IS
BEGIN
SELECT To_char(Max(num))
INTO sp_code
FROM (SELECT "ordernumber" num
FROM "purchaseorder"
WHERE ROWNUM = 1
ORDER BY "pkpurchaseorderid" DESC)
WHERE ROWNUM = 1;
SELECT Substr(sp_code, 10, 2)
INTO sp_code
FROM "purchaseorder";
END newpo_code;
but when i run it from code level
it is giving me exception
ORA-01422: exact fetch returns more than requested number of rows
What am I missing here?
I searched this exception but found no helpful results.
There is not much to go on, but most likely this is the line failing:
select substr(SP_CODE,10,2) into SP_CODE from "PurchaseOrder";
Why? Because there are probably more than 1 row in the PurchaseOrder table, which field you are trying to fit in one variable, SP_CODE.
You probably need a where clause on PurchaseOrder.
PROCEDURE Newpo_code(sp_code OUT VARCHAR2)
IS
BEGIN
SELECT To_char(Max(num))
INTO sp_code
FROM (SELECT "ordernumber" num
FROM "purchaseorder"
WHERE ROWNUM = 1
ORDER BY "pkpurchaseorderid" DESC)
WHERE ROWNUM = 1;
SELECT Substr(sp_code, 10, 2)
INTO sp_code
FROM dual;
END newpo_code;
Done!
Thanks anyways.

pl-sql include column names in query

A weird request maybe but. My boss wants me to create an admin version of a page we have that displays data from an oracle query in a table.
The admin page, instead of displaying the data (query returns 1 row), needs to return the table name and column name
Ex: Instead of:
Name Initial
==================
Bob A
I want:
Name Initial
============================
Users.FirstName Users.MiddleInitial
I realize I can do this in code but would rather just modify the query to return the data I want so I can leave the report generation code mostly alone.
I don't want to do it in a stored procedure.
So when I spit out the data in the report using something like:
blah blah = MyDataRow("FirstName")
I can leave that as is but instead of it displaying "BOB" it would display "Users.FirstName"
And I want to do the query using select * if possible instead of listing all the columns
So for each of the columns I am querying in the * , I want to get (instead of the column value) the tablename.ColumnName or tablename|columnName
hope you are following- I am confusing myself...
pseudo:
select tablename + '.' + Columnname as WhateverTheColumnNameIs
from Table1
left join Table2 on whatever...
Join Table_Names on blah blah
Whew- after writing all this I think I will just do it on the code side.
But if you are up for it maybe a fun challenge
Oracle does not provide an authentic way(there is no pseudocolumn) to get the column name of a table as a result of a query against that table. But you might consider these two approaches:
Extract column name from an xmltype, formed by passing cursor expression(your query) in the xmltable() function:
-- your table
with t1(first_name, middle_name) as(
select 1,2 from dual
), -- your query
t2 as(
select * -- col1 as "t1.col1"
--, col2 as "t1.col2"
--, col3 as "t1.col3"
from hr.t1
)
select *
from ( select q.object_value.getrootelement() as col_name
, rownum as rn
from xmltable('//*'
passing xmltype(cursor(select * from t2 where rownum = 1))
) q
where q.object_value.getrootelement() not in ('ROWSET', 'ROW')
)
pivot(
max(col_name) for rn in (1 as "name", 2 as "initial")
)
Result:
name initial
--------------- ---------------
FIRST_NAME MIDDLE_NAME
Note: In order for column names to be prefixed with table name, you need to list them
explicitly in the select list of a query and supply an alias, manually.
PL/SQL approach. Starting from Oracle 11g you could use dbms_sql() package and describe_columns() procedure specifically to get the name of columns in the cursor(your select).
This might be what you are looking for, try selecting from system views USER_TAB_COLS or ALL_TAB_COLS.

Oracle complex query help required

Can anyone help me getting the output data from oracle database with below conditions.
1.data for each mobile number with last updated ( latest date ) to be copied to an output file.
Note -- there can be multiple entries for single mobile number with different date.
TABLE STRUCTURE AS BELOW.
SQL> desc jtoom.mnp_port_nos_prbt_view;
Name Null? Type
----------------------------------------- -------- ----------------------------
LSA VARCHAR2(144)
MSISDN VARCHAR2(144)
RECIPIENT VARCHAR2(144)
DONOR VARCHAR2(144)
LRN VARCHAR2(144)
DT_STAMP DATE
Something similar to this may work:
select column_name, max(dt_stamp) max_dt_stamp
from table_or_view
group by column_name
This should do the trick:
SELECT DISTINCT A.Column_Name, A.Dt_Stamp
FROM jtoom.mnp_port_nos_prbt_view A
WHERE A.Dt_Stamp = (SELECT Max(B.Dt_Stamp) FROM jtoom.mnp_port_nos_prbt_view B WHERE B.Column_Name = A.Column_Name)

Resources