I have a list of 9 digit IDs in a table I called "numbers", with one column called "ID". I want to use those in a subquery to look for specific rows in a table called artransaction. The problem is that in the transactionid column in artransaction, it has a zero in front of the 9 digit ID.
So if I do:
select * from artransaction
where transactionid in lpad((select id from numbers where rownum=1),10,'0');
It comes back with a result. But if I do:
select * from artransaction
where transactionid in lpad((select id from numbers),10,'0');
It says "single-row subquery returns more than one row"
Is it possible to put in a subquery in LPAD?
You should rewrite that query. Here's an example based on Scott's EMP table - I want to select rows that contain COMM which looks like the ones stored in the NUMBERS table.
SQL> select ename, comm from emp order by ename;
ENAME COMM
---------- ----------
ALLEN 300
BLAKE
CLARK
FORD
JAMES
JONES
KING
MARTIN 1400
MILLER
SMITH
TURNER 0
WARD 500
12 rows selected.
SQL>
Sample NUMBERS table:
SQL> create table numbers (comm number);
Table created.
SQL> insert into numbers values (14);
1 row created.
SQL> insert into numbers values (50);
1 row created.
SQL> insert into numbers values (3);
1 row created.
SQL> select * From numbers;
COMM
----------
14
50
3
SQL>
Testing:
SQL> -- This one will work because of the ROWNUM = 1 condition, which returns a single value
SQL> select * from emp
2 where comm in rpad((select comm from numbers where rownum = 1), 4, '0');
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- ---------- ---------- ---------- ----------
7654 MARTIN SALESMAN 7698 28.09.1981 1250 1400 30
SQL> -- This will result in error because NUMBERS contain several values
SQL> select * from emp
2 where comm in rpad((select comm from numbers), 4, '0');
where comm in rpad((select comm from numbers), 4, '0')
*
ERROR at line 2:
ORA-01427: single-row subquery returns more than one row
SQL> -- So - rewrite it
SQL> select * from emp
2 where comm in (select rpad(comm, 3, '0') from numbers);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- ---------- ---------- ---------- ----------
7521 WARD SALESMAN 7698 22.02.1981 1250 500 30
7499 ALLEN SALESMAN 7698 20.02.1981 1600 300 30
SQL>
Or, applied to your query:
select * from artransaction
where transactionid in (select lpad(id, 10, '0') from numbers);
Related
Structure of two tables in the database are as below.
1) Department table:
Dept_Id number(5) primary key,
Sept_Name varchar2(20),
Employee_strength number(4) not null.
2)Employee table:
E_Id number(5),
E_Name varchar2(20),
Designation varchar2(20),
D_ID number(5) references Department table Dept_ID.
A pl/sql program block to print the name the departments which has employees having the designation as "SE" is to be written and if no record in the department table fulfilling the given conditions found ,code should print the message "No record found" and if the record found code has to print Department name.
Please Help.
Here's one option (based on tables similar to yours; these belong to Scott).
I'll search for a SALESMAN.
SQL> break on deptno
SQL> select distinct d.deptno, e.job
2 from dept d left join emp e on e.deptno = d.deptno
3 order by d.deptno, e.job;
DEPTNO JOB
---------- ---------
10 CLERK
MANAGER
PRESIDENT
20 ANALYST
CLERK
MANAGER
30 CLERK
MANAGER
SALESMAN --> only department 30 has SALESMEN
40
10 rows selected.
SQL>
PL/SQL block:
SQL> set serveroutput on
SQL> declare
2 l_exists number(1);
3 begin
4 for cur_d in (select d.deptno, d.dname from dept d order by d.deptno) loop
5 select max(1)
6 into l_exists
7 from emp e
8 where e.deptno = cur_d.deptno
9 and e.job = 'SALESMAN';
10
11 dbms_output.put_line(cur_d.deptno || ' - ' ||
12 case when l_exists = 1 then cur_d.dname
13 else 'no record found'
14 end);
15 end loop;
16 end;
17 /
10 - no record found
20 - no record found
30 - SALES
40 - no record found
PL/SQL procedure successfully completed.
SQL>
If you want distinct department names then use the distinct() function in the SQL query.
I am using inner join to query the two table based on they have the same department id and department name is "SE".
Here are the steps to be followed:
declare the block(anonymous in this case)
write the SQL query for the cursor
begin the block
open the cursor
fetch the rows from the cursor
print the result
close the cursor
if the cursor doesn't contain any rows, so check for this condition
close the block
DECLARE
CURSOR C IS SELECT distinct(D.DEPT_NAME) FROM DEPARTMENTS D INNER JOIN EMPLOYEES E ON D.DEPT_ID = E.D_ID AND E.DESIGNATION LIKE 'SE';
RES C%ROWTYPE;
BEGIN
OPEN C;
loop
FETCH C INTO RES;
EXIT WHEN C%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(RES.DEPT_NAME);
end loop;
IF(C%ROWCOUNT=0) then
dbms_output.put_line('No record found');
end if;
END;
/
I have a DB trigger before insert on emp table. I would like to add sal, comm from emp_test table and want to use those value as a default in the emp table, by trigger. Any idea how to do it?
Until you provide answers to questions I posted in a comment, here's how you might do it. See if you can adjust it.
EMP_TEST table contains only one row (which is kind of stupid; you'd rather use DEFAULT value for those columns in the EMP table).
SQL> create table emp_test (sal number, comm number);
Table created.
SQL> insert into emp_test (sal, comm) values (3000, 100);
1 row created.
Trigger takes SAL and COMM values if they are provided; otherwise, it takes values from the EMP_TEST table.
SQL> create or replace trigger trg_bi_emp
2 before insert on emp
3 for each row
4 begin
5 select nvl(:new.sal, t.sal),
6 nvl(:new.comm, t.comm)
7 into :new.sal,
8 :new.comm
9 from emp_test t;
10 end;
11 /
Trigger created.
Testing: I didn't provide SAL value (so trigger will insert EMP_TEST one), but I did provide COMM:
SQL> insert into emp (empno, ename, deptno, sal, comm)
2 values (1, 'Littlefoot', 40, null, 50);
1 row created.
SQL> select * from emp where empno = 1;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- -------- ---------- ---------- ----------
1 Littlefoot 3000 50 40
SQL>
I want to update existing user names to following format user+(value of loop iterator) . Any advice? The current statement shows the value 'app2nd' after execution
UPDATE users
SET user_name = 'user'|| v_count
WHERE id = c_id;
Certainly, you should provide some more information. In the meantime, as I have some time to spare, two options for you: the first one doesn't require any loop (you mentioned) but utilizes the ROWNUM:
SQL> select * from test;
DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SQL> update test set
2 dname = 'user' || rownum --> this
3 where deptno >= 20;
3 rows updated.
SQL> select * From test;
DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 user1 DALLAS
30 user2 CHICAGO
40 user3 BOSTON
SQL>
SQL> rollback;
Rollback complete.
SQL>
Another option, a LOOP I invented as you didn't explain which kind of a loop you have:
SQL> begin
2 for cur_r in (select deptno, dname,
3 row_number() over (order by deptno) rn
4 from dept)
5 loop
6 update test set
7 dname = 'user' || cur_r.rn
8 where deptno = cur_r.deptno;
9 end loop;
10 end;
11 /
PL/SQL procedure successfully completed.
SQL> select * From test;
DEPTNO DNAME LOC
---------- -------------- -------------
10 user1 NEW YORK
20 user2 DALLAS
30 user3 CHICAGO
40 user4 BOSTON
SQL>
If it helps, fine. If not, you know what to do - express yourself in a poetic way.
Need your help in below, i have to achieve below target from my table.
EMP Table
Record Id EMP Id Emp Name Emp Dept
-------- ------- ------- --------
1 123 ABC Sales
2 - 231 PQR DEPT
I want output in below format
Record ID Table Name Column Name column Values
-------- ---------- ----------- -------------
1 EMP EMP Id 123
1 EMP Emp Name ABC
1 EMP EMP Dept Sales
Is this output possible, would be very thankful if someone can provide query with example
You could try something like this with a temporary table.
temp table schema
Record ID Table Name Column Name column Values
QUERY
BEGIN
FOR t IN (SELECT table_name,column_name
FROM all_tab_columns
WHERE table_name='MyTable' and owner='MySchema' and column_name<>'RecordId' ) LOOP
EXECUTE IMMEDIATE
'INSERT INTO temp_table SELECT RecordId,'''||t.table_name||''','''||t.column_name||''','||t.column_name||' FROM ' || t.table_name;
END LOOP;
COMMIT;
END;
/
SELECT *
FROM temp_table
ORDER BY "RecordId";
I have 2 tables in which ID field is common.
I am fetching all records of first table in a cursor.
Then I want to do is that on the basis of each ID from cursor, I want to get the values from second table and then return that.
How can I do that...
Please help !!!
homework?
this is basic SQL. generally you'd join the two tables.
begin
for r_row in (select b.*
from tab1 a
inner join tab2 b
on b.id = a.id)
loop
null; -- do whatever
end loop;
end;
/
if you have an existing cursor and can't change it
eg where your_cursor is just returning an ID column.
begin
open your_cursor;
loop
fetch your_cursor into v_id;
exit when your_cursor%notfound;
for r_row in (select * from tab2 b where b.id = v_id)
loop
null; -- do whatever here.
end loop;
end loop;
end;
/
edit:
as per comments:
some sample data:
SQL> create table table1 (id number primary key, name varchar2(20));
Table created.
SQL> create table table2 (id number, col1 varchar2(20), col2 varchar2(20));
Table created.
SQL> insert into table1 values (1, 'test');
1 row created.
SQL> insert into table1 values (2, 'foo');
1 row created.
SQL>
SQL> insert into table2 values (1, 'John', 'Smith');
1 row created.
SQL> insert into table2 values (1, 'Peter', 'Jones');
1 row created.
SQL> insert into table2 values (1, 'Jane', 'Doe');
1 row created.
SQL> insert into table2 values (2, 'Nina', 'Austin');
1 row created.
SQL> insert into table2 values (2, 'Naman', 'Goyal');
1 row created.
SQL> commit;
Commit complete.
create a type to hold the return structure. note the datatypes NEED to match the datatypes of the tables table1 and table2 (%type won't work, so make sure they match)
SQL> create type my_obj as object (
2 id number,
3 name varchar2(20),
4 col1 varchar2(20),
5 col2 varchar2(20)
6 );
7 /
Type created.
SQL> create type my_tab as table of my_obj;
2 /
Type created.
now create your function (you can put this in a package if, in your real code, you have it that way).
SQL> create function function1
2 return my_tab pipelined
3 is
4 begin
5 for r_row in (select t1.id, t1.name, t2.col1, t2.col2
6 from table1 t1
7 inner join table2 t2
8 on t1.id = t2.id)
9 loop
10 pipe row(my_obj(r_row.id, r_row.name, r_row.col1, r_row.col2));
11 end loop;
12 end;
13 /
Function created.
SQL>
SQL> select *
2 from table(function1);
ID NAME COL1 COL2
---------- -------------------- -------------------- --------------------
1 test John Smith
1 test Peter Jones
1 test Jane Doe
2 foo Nina Austin
2 foo Naman Goyal
you could pass inputs if required into that function eg table(function1('a', 'b')); etc..