Row to column comma seperated
CREATE TABLE Colors
Color VARCHAR(32)
INSERT into Colors SELECT 'red' from dual
INSERT into Colors SELECT 'orange' from dual
INSERT into Colors SELECT 'blue' from dual
INSERT into Colors SELECT 'green' from dual
Can i do this with out any cursor or loop or a plsql block? can we use some recursive mechanisms like start with connect by
You mean like this?
In 11gR2.
WITH t AS
(SELECT 'red' color
FROM dual
UNION ALL
SELECT 'orange'
FROM dual
UNION ALL
SELECT 'blue'
FROM dual
UNION ALL
SELECT 'green' FROM dual)
SELECT listagg (color, ',') within group (order by 1) FROM t;
SQL> WITH t AS
2 (SELECT 'red' color
3 FROM dual
4 UNION ALL
5 SELECT 'orange'
6 FROM dual
7 UNION ALL
8 SELECT 'blue'
9 FROM dual
10 UNION ALL
11 SELECT 'green' FROM dual)
12 SELECT listagg(color, ',') within GROUP(ORDER BY 1) colors FROM t;
COLORS
blue,green,orange,red
SQL>
SQL> select * from v$version;
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
PL/SQL Release 11.2.0.1.0 - Production
CORE 11.2.0.1.0 Production
TNS for Linux: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - ProductionEdited by: RPuttagunta on Nov 19, 2010 4:39 PM
Added more info.
Similar Messages
-
Splitting comma seperated column data into multiple rows
Hi Gurus,
Please help me for solving below scenario. I have multiple value in single column with comma seperated values and my requirement is load that data into multiple rows.
Below is the example:
Source Data:
Product Size Stock
ABC X,XL,XXL,M,L,S 1,2,3,4,5,6
Target Data:
Product Size Stock
ABC X 1
ABC XL 2
ABC XXL 3
ABC M 4
ABC L 5
ABC S 6
Which transformation we need to use for getting this output?
Thanks in advance !Hello,
Do you need to do this tranformation through OWB mapping only? And can you please tell what type of source you are using? Is it a flat file or a table?
Thanks -
I have a table, much like the one below:-
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
John
Yes
Paul
No
Dave
Jay
No
Matt
Yes
Yes
Karl
Lois
Jane
Maybe
Anna
Barry
No
Yes
Maybe
I want to populate a cell on another sheet with the column headers if the row contains text. For examplein the case of 'Matt', the value I want returned is 'E, R' becuase there is text in the 'Matt' Row in columns E and R
Anyone have any ideas?
Thanks,
KarlHi Hans,
Thanks for that. It works to an extent in that it returns the correct Column, but I actually want it to return the Column heading. It's my fault for not making it clear, I should have used different names for the column headings rather than just A to S......apologies.
Other than that, it does work, but if you have any suggestions on how to get the actual column heading, that would be great.
For example:-
Mon
Tue
Wed
Thu
Fri
Sat
Sun
Mon
Tue
Wed
Thu
Fri
Sat
Sun
Mon
Tue
Wed
Thu
Fri
John
Paul
Yes
Dave
Jay
Yes
No
Matt
Karl
Yes
Lois
Yes
Jane
Anna
Barry -
Hello,
I want to create stored procedure which will give output rows from "values that are passed as one parameter (comma seperated) to store procedure".
Suppose ,
Parameter value : person 1,person2,person3
table structure :
Project Name | officers 1 | officers 2
here, officers 1 or officers 2 may contain names of multiple people.
expected OUTPUT : distinct list(rows) of projects where person 1 or person 2 or person 3 is either officer1 or officer 2.
please explain or provide solution in detail
- ThanksHi Visakh,
Thanks for reply.
But the solution you provided giving me right output only if officer 1 or officer 2 contains single value , not with comma seperated value.
Your solution is working fine for following scenario :
Project
Officers 1
Officers 2
p1
of11
off21
p2
of12
off22
with parameter : of11,off22 : it will give expected output
And its not working in case of :
Project
Officers 1
Officers 2
p1
of11,of12
off21,off23
p2
of12,of13
off22,off24
with parameter : of11,off22 : it will not give any row in output
I need patten matching not exact match :)
ok
if thats the case use this modified logic
CREATE PROC GetProjectDetails
@PersonList varchar(5000)
AS
SELECT p.*
FROM ProjectTable p
INNER JOIN dbo.ParseValues(@PersonList,',')f
ON ',' + p.[officers 1] + ',' LIKE '%,' + f.val + ',%'
OR ',' + p.[officers 2] + ',' LIKE '%,' + f.val + ',%'
GO
Keep in mind that what you've done is a wrong design approach
You should not be storing multiples values like this as comma separated list in a single column. Learn about normalization . This is in violation of 1st Normal Form
Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
My MSDN Page
My Personal Blog
My Facebook Page -
Comma seperated Column, to get details?
how to do, when Table1 has Column with comma seperated IDs, details are in the Table2.
Table 1
ID Col2
1 10,12
2 18,12
3 5,3
4 10
Table 2
col1 col2
3 new
5 old
10 semi
12 mild
18 very mild
a query/pl sql to get the results in:
Results:
ID Col2
1 10
1 12
2 18
2 12
3 5
3 3
4 10but fails if the column has more number of seperated valuesWhat do you mean? Do you get an error? Or the wrong results?
This works for me on 10gXE:
BANNER
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
PL/SQL Release 10.2.0.1.0 - Production
CORE 10.2.0.1.0 Production
TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
NLSRTL Version 10.2.0.1.0 - Production
SQL> drop table t;
Table dropped.
SQL> create table t as
2 select 1 id, '12,13' col from dual union
3 select 2 id, '10,11,12,13' col from dual union
4 select 3 id, '1,2' col from dual union
5 select 4 id, '12,13,14,15' col from dual union
6 select 5 id, '1,2,3,4,5,6,7,8' col from dual union
7 select 6 id, '1' col from dual union
8 select 7 id, '100,101,102' col from dual union
9 select 8 id, '21,22,23,24,25,26,27,28,29,30,31' col from dual;
Table created.
SQL> select id
2 , column_value
3 from ( select id
4 , ','||col||',' col
5 from t
6 )
7 , table(cast(multiset(select substr( col
8 , instr (col, ',', 1, level ) + 1
9 , instr (col, ',', 1, level+1) - instr (col, ',', 1, level) -1
10 )
11 from dual
12 connect by level <= length(col)-length(replace(col,',',''))-1
13 )
14 as sys.odcinumberlist
15 )
16 );
ID COLUMN_VALUE
1 12
1 13
2 10
2 11
2 12
2 13
3 1
3 2
4 12
4 13
4 14
4 15
5 1
5 2
5 3
5 4
5 5
5 6
5 7
5 8
6 1
7 100
7 101
7 102
8 21
8 22
8 23
8 24
8 25
8 26
8 27
8 28
8 29
8 30
8 31
35 rows selected. -
Hi,
This might be a really dumb one to ask but I am currently working on a table that has sequential data for steps that an invoice goes through in a particular system. Here is how it looks:
ID InvoiceID
InvoiceSteps
Timestamp
283403 0000210121_0002_2013
Post FI Invoice
2013-07-01 19:07:00.0000000
389871 0000210121_0002_2013
Clear Invoice
2013-08-25 14:02:00.0000000
Here is my extremely slow query that converts multiple rows of an invoice into a single one with 'InvoiceSteps' listed according to their timestamps in a sequential manner separated by commas.
SELECT [InvoiceID],
[InvoiceSteps] = STUFF((
SELECT ',' + ma.InvoiceSteps
FROM invoices ma
WHERE m.InvoiceID = ma.InvoiceID
ORDER BY [Timestamp]
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM invoices m
GROUP BY InvoiceID
ORDER BY InvoiceID;
Here is the end result:
InvoiceID InvoiceSteps
0000210121_0002_2013
Post FI Invoice,Clear Invoice
My question: How can I improve the query so that it can process thousands of records as fast as possible (>600K in this case).
Thanks you!There are many methods to concatenate the rows to columns. Assuming you have necessary indexes to support your query as Rishabh suggested, if you still find issues with performance, then you need to look at various other approaches as well. I have seen at
certain places(huge data), CLR outperformed . Having said, we need to assess each and come to a conclusion for your scenario.
Refer the below link for various approach, (please also look at the comment session as well):
https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/ -
Column should display comma seperated value.
Hi All,
Iam working on Reports6i.
In my data model i have a query which gives some product names(only one column), i need to display those product names with a comma seperator.
Just like Product1,Product2,....
Can anybody guide me as this is very urgent.
Thanks in Advance
Chinni.something like this ?
WITH DATA AS (SELECT 'X' product,1 order_id FROM DUAL
UNION ALL
SELECT 'Y' product,1 order_id FROM DUAL
UNION ALL
SELECT 'Z' product,1 order_id FROM DUAL
UNION ALL
SELECT 'XX' product,2 order_id FROM DUAL
UNION ALL
SELECT 'YY' product,2 order_id FROM DUAL
UNION ALL
SELECT 'ZZ' product,2 order_id FROM DUAL
SELECT LTRIM(sys_connect_by_path(product,','), ',') PRODUCTS
FROM (SELECT product,
order_id,
row_number() OVER (partition by order_id order by product) RN,
count(product) OVER (partition by order_id) MAXROW
FROM data)
WHERE RN=MAXROW CONNECT BY PRIOR RN+1=RN
AND PRIOR ORDER_ID=ORDER_ID START WITH RN=1 -
Have a column which is having comma seperated values.. and i am trying to s
Have a column which is having comma seperated values.. and i am trying to seperate it.
I am trying to create a stored procedure ..Version 11g xe. .and apex version 4..
Here is the part of code..I cant make a procedure. .cause my statement consist with clause..
create or replace procedure ins_adv_invoice
(mmagazine_no number,madvtno number,missueno number,msection varchar2,mpagenumber varchar2,msalesman_code varchar2)
is
cursor cx is with testa as
(select pagenumber name from advertiser)
select regexp_substr(pagenumber, '[^,]+', 1, rownum) result
from advertiser
connect by level <= length(regexp_replace(pagenumber, '[^,]+')) + 1
where advt_no = madvtno;
begin
for xxx in cx
loop
insert into adv_invoice (magazine_no,advtno,adissue,section,page_number,salesman_code)
values (mmagazine_no,madvtno,missueno,msection,xxx.result,msalesman_code);
end loop;
end;
But when i run this .. it doesnt create procedure. .I get he following error..
LINE/COL ERROR
5/14 PL/SQL: SQL Statement ignored
9/69 PL/SQL: ORA-00933: SQL command not properly ended
SQL>
Still not able to figure it out..Can any one help..
ThanksChange the query to swap the last two lines:
cursor cx is with testa as
(select pagenumber name from advertiser)
select regexp_substr(pagenumber, '[^,]+', 1, rownum) result
from advertiser
where advt_no = madvtno
connect by level <= length(regexp_replace(pagenumber, '[^,]+')) + 1;
... -
Mapping a column with comma seperated values
Hi,
I have two tables
1. Tasks (task_id, task_description)
2. Task_assignment (username, task_assignment_value)
the task_assignment_value has a comma seperated list of task_ids.
What is the best ways to map the tables ?
Thanks in advance.
Moinuddin MohammedI have a couple of attributes where I do this. From TopLink's perspective, I just map it as a String. Then, in my accessors for the attribute, I transform the primitive between the String and an Array or however the rest of the app wants to see the attribute.
Here's an example that's actually more complicated than absolutely necessary. The mapped attributed is indicatorValueListString. It is lazily converted to an Array of Enums when it is first accessed. And it is converted back to a String in the preWriteEventCallback that is mapped in the TopLink descriptor.
This implementation attempts to minimize the number of times the String<->Array conversion takes place, but if that's not a concern, it could be made much more simple. Also, at my company we privately manage collections with the Collection classes for dynamic allocation, but publicly exchange Arrays for type-safety. This could also be factored out. ValuedEnumUtils basically manages asking the enum for its delimiter and performing the actual conversion between a String and an Array or back.
private String indicatorValueListString;
private List indicatorValueSelections;
private List indicatorValueSelections() {
if (indicatorValueSelections == null) {
indicatorValueSelections = new ArrayList();
if (indicatorValueListString != null) {
indicatorValueSelections =
java.util.Arrays.asList(ValuedEnumUtils.decodeEnumString(
IndicatorValueEnum.class,indicatorValueListString));
return indicatorValueSelections;
private void indicatorValueSelections(List newIndicatorValueSelections) {
indicatorValueSelections = newIndicatorValueSelections;
public IndicatorValueEnum[] getIndicatorValueSelections() {
return (IndicatorValueEnum[])indicatorValueSelections().toArray(new IndicatorValueEnum[0]);
public void setIndicatorValueSelections(IndicatorValueEnum[] newIvSelections) {
indicatorValueSelections(java.util.Arrays.asList(newIvSelections));
public boolean addIndicatorValueSelection(IndicatorValueEnum anIvEnum) {
return indicatorValueSelections().add(anIvEnum);
public boolean removeIndicatorValueSelection(IndicatorValueEnum anIvEnum) {
return indicatorValueSelections().remove(anIvEnum);
public void preWriteEventCallback(DescriptorEvent aDescriptorEvent) {
// Note: Not using accessor to avoid lazy initialization if no changes
// are necessary.
if (indicatorValueSelections != null) {
indicatorValueListString =
ValuedEnumUtils.encodeEnumString((ValuedEnum[])indicatorValueSelections.toArray());
} -
Count the number of elements in comma seperated list of values
Hello Friends,
I have a string with comma seperated list of values say
String v = 34343,erere,ererere,sdfsdfsdfs,4454,5454,dsfsdfsfsd,fsdfsdfsdfs,dfdsfsdfsdfs,sdsfdsf,ererdsdsd45454,fsdfsdfs
Want to count how many elements are existing in this string .
Thanks/KumarHi, Kumar,
REGEXP_COUNT, which Hoek used, is handy, but it only works in Oracle 11. Which version of Oracle are you using?
In any version of Oracle, you can count the commas by seeing how much the string shrinks when you remove them.
LENGTH (str) + 1 - LENGTH (REPLACE (str, ',')) Can str have multiple commas in a row? What if there's nothing between consecutive commas, or nothing by whitespace? Can str begin or end with a comma? Can str consist of nothing but commas? Depending on your answers, you may have to change things. You might want
REGEXP_COUNT ( str
, '[^,]+'
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say which version of Oracle you're using.
See the forum FAQ {message:id=9360002} -
Convert rows to columns in sql database
Hi Team,
I have a table called as ABC in test schema which have got 3 columns
ABC
COL1 VARCHAR2(10)
COL2 VARCHAR2(10)
COL3 VARCHAR2(10)
The dat in ABC table is as follows
ABC
COL1 COL2 COL3
A B C
I wanted to write a sql query which will give me
COL
A
B
C
Appreciate your help on the above?
Thanks & Regards,
Thakur Manoj RGurjeet wrote:
with t as ( select deptno ||',' || dname || ',' || loc as abc from dept where deptno =10)
select regexp_substr(abc,'[^,]+', 1, level) from t
connect by regexp_substr(abc, '[^,]+', 1, level) is not null
That is a completely wrong answer.
The OP was not asking how to split a comma seperated string, he was asking how to unpivot individual columns to a single column.
That can be achieved using the UNPIVOT functionality in SQL, if the database version supports it, or if not something as simple as:
SQL> ed
Wrote file afiedt.buf
1 with t as (select 'A' as col1, 'B' as col2, 'C' as col3 from dual union all
2 select 'X','Y','Z' from dual)
3 --
4 -- end of test data
5 --
6 select decode(rn,1,col1,2,col2,col3) as col
7 from t
8* cross join (select rownum rn from dual connect by rownum <= 3)
SQL> /
C
A
X
B
Y
C
Z
6 rows selected. -
How to make comma seperated file
hi
I have a select statement that looks like below. I want to make comma seperated file for the selected columns. How to write it?
SELECT MM.DAL_NUMBER,
'19-NOV-2009' as WSS_CE,
CPN_INT,
TRADE_DATE,
MX_DATE "LAST_DATE",
CUSTOMER_SPECIF CUST_GID,
NAME_SHORT CUST_NAME_SHORT
from my_table;
if you could provide me with exact query.
ThanksSlightly more generic approach...
As sys user:
CREATE OR REPLACE DIRECTORY TEST_DIR AS '\tmp\myfiles'
GRANT READ, WRITE ON DIRECTORY TEST_DIR TO myuser
/As myuser:
CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2
,p_dir IN VARCHAR2
,p_header_file IN VARCHAR2
,p_data_file IN VARCHAR2 := NULL) IS
v_finaltxt VARCHAR2(4000);
v_v_val VARCHAR2(4000);
v_n_val NUMBER;
v_d_val DATE;
v_ret NUMBER;
c NUMBER;
d NUMBER;
col_cnt INTEGER;
f BOOLEAN;
rec_tab DBMS_SQL.DESC_TAB;
col_num NUMBER;
v_fh UTL_FILE.FILE_TYPE;
v_samefile BOOLEAN := (NVL(p_data_file,p_header_file) = p_header_file);
BEGIN
c := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
d := DBMS_SQL.EXECUTE(c);
DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
FOR j in 1..col_cnt
LOOP
CASE rec_tab(j).col_type
WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);
WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);
ELSE
DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
END CASE;
END LOOP;
-- This part outputs the HEADER
v_fh := UTL_FILE.FOPEN(upper(p_dir),p_header_file,'w',32767);
FOR j in 1..col_cnt
LOOP
v_finaltxt := ltrim(v_finaltxt||','||lower(rec_tab(j).col_name),',');
END LOOP;
-- DBMS_OUTPUT.PUT_LINE(v_finaltxt);
UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
IF NOT v_samefile THEN
UTL_FILE.FCLOSE(v_fh);
END IF;
-- This part outputs the DATA
IF NOT v_samefile THEN
v_fh := UTL_FILE.FOPEN(upper(p_dir),p_data_file,'w',32767);
END IF;
LOOP
v_ret := DBMS_SQL.FETCH_ROWS(c);
EXIT WHEN v_ret = 0;
v_finaltxt := NULL;
FOR j in 1..col_cnt
LOOP
CASE rec_tab(j).col_type
WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
v_finaltxt := ltrim(v_finaltxt||','||v_n_val,',');
WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
v_finaltxt := ltrim(v_finaltxt||','||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),',');
ELSE
v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
END CASE;
END LOOP;
-- DBMS_OUTPUT.PUT_LINE(v_finaltxt);
UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
END LOOP;
UTL_FILE.FCLOSE(v_fh);
DBMS_SQL.CLOSE_CURSOR(c);
END;This allows for the header row and the data to be written to seperate files if required.
e.g.
SQL> exec run_query('select * from emp','TEST_DIR','output.txt');
PL/SQL procedure successfully completed.Output.txt file contains:
empno,ename,job,mgr,hiredate,sal,comm,deptno
7369,"SMITH","CLERK",7902,17/12/1980 00:00:00,800,,20
7499,"ALLEN","SALESMAN",7698,20/02/1981 00:00:00,1600,300,30
7521,"WARD","SALESMAN",7698,22/02/1981 00:00:00,1250,500,30
7566,"JONES","MANAGER",7839,02/04/1981 00:00:00,2975,,20
7654,"MARTIN","SALESMAN",7698,28/09/1981 00:00:00,1250,1400,30
7698,"BLAKE","MANAGER",7839,01/05/1981 00:00:00,2850,,30
7782,"CLARK","MANAGER",7839,09/06/1981 00:00:00,2450,,10
7788,"SCOTT","ANALYST",7566,19/04/1987 00:00:00,3000,,20
7839,"KING","PRESIDENT",,17/11/1981 00:00:00,5000,,10
7844,"TURNER","SALESMAN",7698,08/09/1981 00:00:00,1500,0,30
7876,"ADAMS","CLERK",7788,23/05/1987 00:00:00,1100,,20
7900,"JAMES","CLERK",7698,03/12/1981 00:00:00,950,,30
7902,"FORD","ANALYST",7566,03/12/1981 00:00:00,3000,,20
7934,"MILLER","CLERK",7782,23/01/1982 00:00:00,1300,,10The procedure allows for the header and data to go to seperate files if required. Just specifying the "header" filename will put the header and data in the one file.
Adapt to output different datatypes and styles are required. -
Inserting comma seperated values
I created a stored procedure that creates an order_id. Using this id, the products and their pricetag are inserted. Hereafter the garnishes are inserted for each product.
Creating an order id and inserting the products and their pricetag are working. The problem is at the inserting of garnishes.
The data is received by parameters, and I have also created a user defined type: where garnishId holds the comma seperated ids.
CREATE TYPE [dbo].[ppg] AS TABLE(
[ProductId] [int] NULL,
[PriceId] [int] NULL,
[garnishId] [VARCHAR](MAX) NULL
this is the stored procedure:
ALTER PROCEDURE [dbo].[sp_create_order]
(@userId uniqueidentifier, @productPriceGarnishes dbo.ppg READONLY, @comment varchar(250))
AS
BEGIN
DECLARE @orderId int
DECLARE @orderDetailId int
INSERT INTO orders (user_id, confirmed,comment) values(@userId,0,@comment);
--Select last inserted PK
SELECT @orderId=SCOPE_IDENTITY()
-- insert products and price tag using @orderId
INSERT INTO order_detail (order_id, product_id,price_id)
SELECT @orderId, p.ProductId,
p.PriceId
FROM @productPriceGarnishes p
SELECT @orderDetailId=SCOPE_IDENTITY()
-- insert garnishes using the orderDetailId
INSERT INTO order_detail_garnish (order_detail_id,garnish_id)
SELECT @orderDetailId, (SELECT * FROM SplitDelimiterString(p.garnishId))
FROM @productPriceGarnishes p
END
RETURN @orderId
I found a function that splits the string by a delimiter in this website:
http://www.codeproject.com/Tips/586395/Split-comma-separated-IDs-to-ge
Where you can retrieve the ids by this query:
(SELECT * FROM SplitDelimiterString(p.garnishId)
The problem is that I don't know how to add these ids with their corresponding orderDetailId, after each product is added.Unfortunately it appears you assume too much. Presumably the reason you chose to define @productPriceGarnishes as a table is to support the creation of multiple rows. And you use these rows to insert into the order_detail table which has an identity
column as the primary key (again, presumably). So the question then becomes how do you get the identity values for ALL of the inserted rows? You can't do that with SCOPE_IDENTITY - your code currently is designed with the assumption that there
is only one row to be inserted. To work around that limitation you need to use the output clause (examples can be found by searching).
Next comes another problem. How do you know which identity value is assigned to which row of your table variable during the insert? You need some sort of natural key to associate the inserted rows with the rows in the table variable. Do
you have one? Before you think you do, you need to think about what restrictions are placed on the content of the table variable (if any). Is it possible to have multiple rows with the same values for ProductId and PriceId? Do not assume
- you need to be certain that this is or is not a possibility.
Assuming that the rows are unique (which simplifies things greatly), you associate the inserted order_detail rows to the table variable via something like:
select ... from @ins_detail as ins inner join @productPriceGarnishes as ppg
on ins.ProductId = ppg.ProductId and ins.PriceId = ppg.PriceId
Note that @ins_detail is a table variable that you would declare and populate via the output clause. It will contain the identity values for each row that you inserted. With that, you can then generate the rows that you need to insert into the garnish
table by applying the results of your splitter function. Which is a step that I'll skip for now since you have much reading and work to do.
Now some last comments. I am suspicious of a column named PriceId. That is not a good sign - price is an attribute of something and not the basis of a relationship between tables. The use of identity columns (especially as primary keys)
can be a problem - and this is one good example. Based on what I've just written and its assumptions, the natural key for order_detail is (order_id, product_id, price_id) - why do you need an identity column? Again, searching will find past
discussions about identity columns and their usage. -
Table name input. and output i need all rows and columns using procedures
hi,
question: table name input. and output i need all rows and columns by using procedures.
thanks,
To AllAn example of using DBMS_SQL package to execute dynamic SQL (in this case to generate CSV data in a file)...
As sys user:
CREATE OR REPLACE DIRECTORY TEST_DIR AS '\tmp\myfiles'
GRANT READ, WRITE ON DIRECTORY TEST_DIR TO myuser
/As myuser:
CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2
,p_dir IN VARCHAR2
,p_header_file IN VARCHAR2
,p_data_file IN VARCHAR2 := NULL) IS
v_finaltxt VARCHAR2(4000);
v_v_val VARCHAR2(4000);
v_n_val NUMBER;
v_d_val DATE;
v_ret NUMBER;
c NUMBER;
d NUMBER;
col_cnt INTEGER;
f BOOLEAN;
rec_tab DBMS_SQL.DESC_TAB;
col_num NUMBER;
v_fh UTL_FILE.FILE_TYPE;
v_samefile BOOLEAN := (NVL(p_data_file,p_header_file) = p_header_file);
BEGIN
c := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
d := DBMS_SQL.EXECUTE(c);
DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
FOR j in 1..col_cnt
LOOP
CASE rec_tab(j).col_type
WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);
WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);
ELSE
DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
END CASE;
END LOOP;
-- This part outputs the HEADER
v_fh := UTL_FILE.FOPEN(upper(p_dir),p_header_file,'w',32767);
FOR j in 1..col_cnt
LOOP
v_finaltxt := ltrim(v_finaltxt||','||lower(rec_tab(j).col_name),',');
END LOOP;
-- DBMS_OUTPUT.PUT_LINE(v_finaltxt);
UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
IF NOT v_samefile THEN
UTL_FILE.FCLOSE(v_fh);
END IF;
-- This part outputs the DATA
IF NOT v_samefile THEN
v_fh := UTL_FILE.FOPEN(upper(p_dir),p_data_file,'w',32767);
END IF;
LOOP
v_ret := DBMS_SQL.FETCH_ROWS(c);
EXIT WHEN v_ret = 0;
v_finaltxt := NULL;
FOR j in 1..col_cnt
LOOP
CASE rec_tab(j).col_type
WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
v_finaltxt := ltrim(v_finaltxt||','||v_n_val,',');
WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
v_finaltxt := ltrim(v_finaltxt||','||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),',');
ELSE
v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
END CASE;
END LOOP;
-- DBMS_OUTPUT.PUT_LINE(v_finaltxt);
UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
END LOOP;
UTL_FILE.FCLOSE(v_fh);
DBMS_SQL.CLOSE_CURSOR(c);
END;This allows for the header row and the data to be written to seperate files if required.
e.g.
SQL> exec run_query('select * from emp','TEST_DIR','output.txt');
PL/SQL procedure successfully completed.Output.txt file contains:
empno,ename,job,mgr,hiredate,sal,comm,deptno
7369,"SMITH","CLERK",7902,17/12/1980 00:00:00,800,,20
7499,"ALLEN","SALESMAN",7698,20/02/1981 00:00:00,1600,300,30
7521,"WARD","SALESMAN",7698,22/02/1981 00:00:00,1250,500,30
7566,"JONES","MANAGER",7839,02/04/1981 00:00:00,2975,,20
7654,"MARTIN","SALESMAN",7698,28/09/1981 00:00:00,1250,1400,30
7698,"BLAKE","MANAGER",7839,01/05/1981 00:00:00,2850,,30
7782,"CLARK","MANAGER",7839,09/06/1981 00:00:00,2450,,10
7788,"SCOTT","ANALYST",7566,19/04/1987 00:00:00,3000,,20
7839,"KING","PRESIDENT",,17/11/1981 00:00:00,5000,,10
7844,"TURNER","SALESMAN",7698,08/09/1981 00:00:00,1500,0,30
7876,"ADAMS","CLERK",7788,23/05/1987 00:00:00,1100,,20
7900,"JAMES","CLERK",7698,03/12/1981 00:00:00,950,,30
7902,"FORD","ANALYST",7566,03/12/1981 00:00:00,3000,,20
7934,"MILLER","CLERK",7782,23/01/1982 00:00:00,1300,,10The procedure allows for the header and data to go to seperate files if required. Just specifying the "header" filename will put the header and data in the one file.
Adapt to output different datatypes and styles are required. -
Rows to column in 11g as single query
I would like to create single row with column name
as ISIN, CUSIP, SEDOL for each row which has desc IS, CU, SE
as below
SQL> select * from test;
CODE DESCR VALUE
10 IS 100
10 CU 200
10 SE 200
20 IS 100
20 CU 200
20 SE 200
The row should looks like below with column name ISIN, CUSIP, SEDOL
CODE ISIN CUSIP SEDOL
10 100 200 200
20 100 200 200
CREATE TABLE TEST
CODE NUMBER(10),
DESCR VARCHAR2(20 BYTE),
VALUE NUMBER(10)
SET DEFINE OFF;
Insert into TEST
(CODE, DESCR, VALUE)
Values
(10, 'IS', 100);
Insert into TEST
(CODE, DESCR, VALUE)
Values
(10, 'CU', 200);
Insert into TEST
(CODE, DESCR, VALUE)
Values
(10, 'SE', 200);
Insert into TEST
(CODE, DESCR, VALUE)
Values
(20, 'IS', 100);
Insert into TEST
(CODE, DESCR, VALUE)
Values
(20, 'CU', 200);
Insert into TEST
(CODE, DESCR, VALUE)
Values
(20, 'SE', 200);
COMMIT;Frank, the query i posted is an eg.
in real i have 200k records in the table.
SQL> explain plan for select * from master_base a, (SELECT * FROM id_xref
2 PIVOT ( max (SECURITY_XREF_NBR)
3 FOR SECURITY_XREF_CD
4 IN ( 'IS' AS isin
5 , 'CU' AS cusip
6 , 'SD' AS sedol
7 )
8 )
9 ) b
10 where a.security_nbr = b.security_nbr(+)
11 ;
Explained.
Elapsed: 00:00:00.23
SQL> set lines 200
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 2437398092
| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 238K| 57M| | 7495 (2)| 00:01:30 |
|* 1 | HASH JOIN OUTER | | 238K| 57M| 8024K| 7495 (2)| 00:01:30 |
| 2 | TABLE ACCESS FULL | MASTER_BASE | 61776 | 7299K| | 825 (3)| 00:00:10 |
| 3 | VIEW | | 238K| 29M| | 4647 (2)| 00:00:56 |
| 4 | HASH GROUP BY PIVOT| | 238K| 15M| 21M| 4647 (2)| 00:00:56 |
| 5 | TABLE ACCESS FULL | ID_XREF | 238K| 15M| | 706 (4)| 00:00:09 |
PLAN_TABLE_OUTPUT
Predicate Information (identified by operation id):
1 - access("A"."sECURITY_NBR"="B"."SECURITY_NBR"(+))
17 rows selected.Edited by: user520824 on Jul 22, 2010 8:28 AM
Edited by: user520824 on Jul 22, 2010 8:31 AM
Maybe you are looking for
-
How to use filter to color cell content
Numbers 3.5.2: I would like the content of a cell to change color, if the value of the number within the cell drops down below a certain value. For instance: as long as the values in the cell stay above 50 -> the number should be displayed black, if
-
HT5409 AVCHD audio does not play with the video clip
iPhoto does not import, or even see the clips, and when QuickTime played the clip off the card itself, no audio is present even though the inspector shows stereo.
-
H264 movie stutters in QuickTime
I have a 1GHz G4, and h264 videos, e.g. movies, play fine in VLC player--perfectly smooth, but most stutter terribly in QT. I just updated from QT 7.0 to 7.6.4, with no improvement. Clearly the system is fast enough to play such movies, at least up t
-
Function 'function name' may not used in sql
Hi Guys, How to call a function in a form level trigger? i created a function in program unit.In timer expired trigger i tried to call a function as select sf1('a') from dual;Im getting below error function sf1 may not use in sqlAdvance thanks
-
Hi, I realize this is the most boring topic in the world, but i just got my new imac, upgraded to QT 7 Pro and now I can't play all the old AVI movies i USED to be able to play on my old mac. I've been at this for an hour or so and downloaded so many