Number of columns in composite key
Hi,
I would like to know ,how many number of columns can be included in a composite primary key.
thanx in advance
Regards
Rupesh S
A composite key like that would have an underlying index created on it and that index has certain limitations.
ORA-01793 maximum number of index columns is 32
Cause: While creating an index, more than 32 columns were specified.
Action: Remove some columns from the index definition. If all the columns indexed are required, split them into two indexes.
It may not be a good idea to have that many columns in the composite key to begin with.
Similar Messages
-
Maximum number of column in Composite Primary Key
Hi
I have read that composite primary key can contain maximum of 32 columns (Oracle 9i).
However I am able to create a primary key on 33 columns. It fails to create primary key on 34 columns. Below are the queries.
DROP TABLE XYZ;
CREATE TABLE XYZ
( N1 NUMBER
,N2 NUMBER
,N3 NUMBER
,N4 NUMBER
,N5 NUMBER
,N6 NUMBER
,N7 NUMBER
,N8 NUMBER
,N9 NUMBER
,N10 NUMBER
,N11 NUMBER
,N12 NUMBER
,N13 NUMBER
,N14 NUMBER
,N15 NUMBER
,N16 NUMBER
,N17 NUMBER
,N18 NUMBER
,N19 NUMBER
,N20 NUMBER
,N21 NUMBER
,N22 NUMBER
,N23 NUMBER
,N24 NUMBER
,N25 NUMBER
,N26 NUMBER
,N27 NUMBER
,N28 NUMBER
,N29 NUMBER
,N30 NUMBER
,N31 NUMBER
,N32 NUMBER
,N33 NUMBER
,N34 NUMBER
,N35 NUMBER
,N36 NUMBER
,N37 NUMBER
,N38 NUMBER
,N39 NUMBER
,N40 NUMBER
,N41 NUMBER
,N42 NUMBER
,N43 NUMBER
,N44 NUMBER
,N45 NUMBER
,N46 NUMBER
,N47 NUMBER
,N48 NUMBER
,N49 NUMBER
,N50 NUMBER
ALTER TABLE XYZ ADD CONSTRAINT XYZ_PK PRIMARY KEY
( N1,N2,N3,N4,N5,N6,N7,N8,N9,N10,N11,N12,N13,N14
,N15,N16,N17,N18,N19,N20,N21,N22,N23,N24,N25,N26
,N27,N28,N29,N30,N31,N32,N33,N34);
ALTER TABLE XYZ ADD CONSTRAINT XYZ_PK PRIMARY KEY
( N1,N2,N3,N4,N5,N6,N7,N8,N9,N10,N11,N12,N13,N14
,N15,N16,N17,N18,N19,N20,N21,N22,N23,N24,N25,N26
,N27,N28,N29,N30,N31,N32,N33);
Can someone let me know the lmit of maximum no. of columns in Primary Key?
Regards
ArunSQL> select * from v$version;
BANNER
Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
PL/SQL Release 9.2.0.1.0 - Production
CORE 9.2.0.1.0 Production
TNS for 32-bit Windows: Version 9.2.0.1.0 - Production
NLSRTL Version 9.2.0.1.0 - Production
SQL> ALTER TABLE XYZ ADD CONSTRAINT XYZ_PK PRIMARY KEY
2 ( N1,N2,N3,N4,N5,N6,N7,N8,N9,N10,N11,N12,N13,N14
3 ,N15,N16,N17,N18,N19,N20,N21,N22,N23,N24,N25,N26
4 ,N27,N28,N29,N30,N31,N32,N33);
Table altered. -
Sort key too long - maximum number of columns in select statement
the sort key too long is caused by either too many group
functions or too many columns selected. Does anyone know the
maximum number of columns that can be selected in one statement ?The Oracle 9i reference states ...
The GROUP BY expression and all of the
nondistinct aggregates functions (for example,
SUM, AVG) must fit within a single database
block.
... and the Oracle 9i SQL Reference states that ...
An order_by_clause can contain no more than 255
expressions.
You could check your own documentation, but i think it will
be the same. -
Trouble with a composite key & unique violation
Hi all
as mentioned yesterday I'm a novice so apologies in advance for any lack of clarity in my question:
I'm doing the standard student estate agent database and I have come across an issue with a composite key.
the table in question follows:
CREATE TABLE Offer
buyer_id CHAR(5) not null references buyer (buyer_id),
property_id CHAR(5) not null references property (property_id),
primary key (BUYER_ID, PROPERTY_ID),
offer_date DATE not null,
offer_time NUMBER(4) not null,
offer_amount NUMBER(10,2) not null
and I have all the other tables in position with data loaded. However, when I try to load data into this table the buyer_id & property_id can be duplicated (it makes sense a buyer could make several offers on the same property).
I'm not sure how to get around it. When I simply remove the primary key line the the next line offer_date.... is not recognized. I'm I missing something obvious? I am not allowed to changed the structure of the table. Do I need another identifier for the composite key?
thanks JoIf you want to stick with natural primary keys, you would probably need to use the combination of (buyer_id, property_id, offer_date), assuming that the same buyer wouldn't make simultaneous offers on the same property. Given that this creates a rather unwieldy key for any child tables to reference, and given that the BUYER and PROPERTY tables appear to have synthetic foreign keys, you would probably want to add an OFFER_ID column to your table that is the primary key for the table and is populated via a sequence.
Justin -
Is it possible to create foreign key from composite key in other table.
SQL> desc PRODUCT_CONFIG_OPTION;
Name Null? Type
CONFIG_ITEM_ID NOT NULL VARCHAR2(20) --composite primary key
CONFIG_OPTION_ID NOT NULL VARCHAR2(20) --composite primary key
CONFIG_OPTION_NAME VARCHAR2(100)
DESCRIPTION VARCHAR2(255)
SEQUENCE_NUM NUMBER(18)
LAST_UPDATED_STAMP TIMESTAMP(6)
LAST_UPDATED_TX_STAMP TIMESTAMP(6)
CREATED_STAMP TIMESTAMP(6)
CREATED_TX_STAMP TIMESTAMP(6)
SQL> DESC PRODUCT_CONFIG_ITEM;
Name Null? Type
CONFIG_ITEM_ID NOT NULL VARCHAR2(20)
CONFIG_ITEM_TYPE_ID VARCHAR2(20)
CONFIG_ITEM_NAME VARCHAR2(100)
DESCRIPTION VARCHAR2(255)
LONG_DESCRIPTION CLOB
IMAGE_URL VARCHAR2(255)
LAST_UPDATED_STAMP TIMESTAMP(6)
LAST_UPDATED_TX_STAMP TIMESTAMP(6)
CREATED_STAMP TIMESTAMP(6)
CREATED_TX_STAMP TIMESTAMP(6)
SQL> desc product;
Name Null? Type
PRODUCT_ID NOT NULL VARCHAR2(20)
PRODUCT_TYPE_ID VARCHAR2(20)
PRIMARY_PRODUCT_CATEGORY_ID VARCHAR2(20)
MANUFACTURER_PARTY_ID VARCHAR2(20)
FACILITY_ID VARCHAR2(20)
INTRODUCTION_DATE TIMESTAMP(6)
SUPPORT_DISCONTINUATION_DATE TIMESTAMP(6)
SALES_DISCONTINUATION_DATE TIMESTAMP(6)
SALES_DISC_WHEN_NOT_AVAIL CHAR(1)
INTERNAL_NAME VARCHAR2(255)
BRAND_NAME VARCHAR2(100)
COMMENTS VARCHAR2(255)
=========
CREATE TABLE PROD_CONFIG_PROD_CONFIG_OPTION (
PRODUCT_ID VARCHAR2(20),
CONFIG_ITEM_ID VARCHAR2(20),
CONFIG_OPTION_ID VARCHAR2(20),
PAGE_NUM_TO NUMBER(18),
ALTERNATE_PAGE_NUM_TO1 NUMBER(18),
ALTERNATE_PAGE_NUM_TO2 NUMBER(18),
ALTERNATE_PAGE_NUM_TO3 NUMBER(18),
LAST_UPDATED_STAMP TIMESTAMP(6),
LAST_UPDATED_TX_STAMP TIMESTAMP(6),
CREATED_STAMP TIMESTAMP(6),
CREATED_TX_STAMP TIMESTAMP(6),
CONSTRAINT PK_PROD_CAT_CONFIG_MOD PRIMARY KEY (PRODUCT_ID),
CONSTRAINT FK_PRODUCT_ID FOREIGN KEY (PRODUCT_ID) REFERENCES PRODUCT(PRODUCT_ID),
CONSTRAINT FK_CONFIG_ITEM_ID FOREIGN KEY (CONFIG_ITEM_ID) REFERENCES PRODUCT_CONFIG_ITEM(CONFIG_ITEM_ID),
CONSTRAINT FK_CONFIG_OPTION_ID FOREIGN KEY (CONFIG_OPTION_ID) REFERENCES PRODUCT_CONFIG_OPTION(CONFIG_OPTION_ID) )
TABLESPACE DATA_SMALL
i try to create this table if i omit 3rd foreign key constraint then table successfully created.but including trd foreign key constraint it return error "ORA-02270: no matching unique or primary key for this column-list"
i checked everything is it possible to create foreign key from composite key in other table.And
CONSTRAINT FK_CONFIG_OPTION_ID FOREIGN KEY (CONFIG_ITEM_ID,CONFIG_OPTION_ID) REFERENCES PRODUCT_CONFIG_OPTION(CONFIG_ITEM_ID,CONFIG_OPTION_ID)
? -
HowTo: construct Composite key using other composite key?
Hello. I don' undestand how is it possible to do.
Please, see my code:
@Entity
@Table(name = "Person", schema = SCHEMA)
public class Person {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
private String medialogyUid;
private String firstName;
private String lastName;
private String patronymic;
private String biography;
@Entity
@IdClass(Convocation.PK.class)
@Table(name = "Convocation", schema = SCHEMA)
public class Convocation {
@Id
private int number;
@Id
@ManyToOne(fetch=FetchType.EAGER, cascade={CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST})
private Institution institution;
private Date beginDate;
private Date endDate;
public Convocation(){
public Convocation(Institution inst, int number, Date beginDate, Date endDate){
this.institution = inst;
this.number = number;
this.beginDate = beginDate;
this.endDate = endDate;
public static final class PK implements Serializable {
public int number;
public int institution;
public PK(){
/**@param number is convocation,number
* @param institution is convocation.institution.id
public PK(int number, int institution){
this.number = number;
this.institution = institution;
@Override
public boolean equals(Object o) {
if (!(o instanceof PK))
return false;
PK oPK = (PK)o;
return this.number == oPK.number && this.institution == oPK.institution;
@Override
public int hashCode() {
return ((number == 0) ? 0 : new Integer(number).hashCode()) ^ ((institution == 0) ? 0 : new Integer(institution).hashCode());
//And finally the last class:
@Entity
@IdClass(DeputyMandate.PK.class)
@Table(name = "DeputyMandate", schema = SCHEMA)
public class DeputyMandate {
@Id
@ManyToOne(fetch=FetchType.EAGER, cascade={CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST})
private Person person;
@Id
@ManyToOne(fetch=FetchType.EAGER, cascade={CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST})
private Convocation convocation;
private Date dateIn;
private Date dateOut;
public static final class PK implements Serializable {
//don't know what to use @Embeddable or what?
}I want DeputyMandate to use composite key. This composite key is based on Person with simple key +(int id)+ and Convocation PK.
Please, tell me how can I make composite key DeputyMandate.PK using simple key from Person and composite key from Convocation.
Edited by: Holod on 27.08.2008 15:52And
CONSTRAINT FK_CONFIG_OPTION_ID FOREIGN KEY (CONFIG_ITEM_ID,CONFIG_OPTION_ID) REFERENCES PRODUCT_CONFIG_OPTION(CONFIG_ITEM_ID,CONFIG_OPTION_ID)
? -
How to restrict number of column exposed by xsoData service at runtime
Hi All,
I have created one xsoData service over calculation view (imported one BW cube).
I want to expose few characteristics of cube and a key figure.
I want to decide this key figure at run time,means if i have say three key figures say quantity, cost and revenue apart of my characteristics.
when i run this service, i should be able to pass key figure name for which i want to see data.
Can i have a variable for column name for this purpose and how i can pass it its value ?
Please suggest.
Regards,
RohitHi Thomas,
Thanks for the reply.
I have already used to restrict the number of columns using 'WITH' keyword.
Say there are 10 characteristics and 10 keyfigures in my calculation view.
Out of which i have exposed 3 chars and 3 KFs using 'WITH' keyword, for keyfigures i want to have one variable or placeholder in my xS ODATA service whose value i want to pass from UI( through XS service URL).
So my service should fetch 3 Characteristics and a keyfigure say qty or cost or revenue.
Please let me know if anything is still not clear.
Regards,
Rohit -
Gettin error while setting column as primary key
Hi I am trying to extract data from XML file
and create one custom table
Its working fine when I try following code
CREATE TABLE xx_PER_ALL_VACANCIES
AS (SELECT x.* FROM hr_api_transactions t, xmltable('//PerAllVacanciesEORow' passing xmltype(transaction_document) columns location_id NUMBER path 'LocationId', organization_id NUMBER path 'OrganizationId', name VARCHAR2(100) path 'Name', creation_date VARCHAR2(15) path 'CreationDate',PeopleGroupId NUMBER path 'PeopleGroupId',REQUISITION_ID NUMBER(15)path 'RequisitionId',COMMENTS LONG() path 'Comments')
x
WHERE t.transaction_ref_table = 'PER_ALL_VACANCIES');but when I try to make Name column as primary key then it gives an error
following is code
CREATE TABLE xx_PER_ALL_VACANCIES
AS (SELECT x.* FROM hr_api_transactions t, xmltable('//PerAllVacanciesEORow' passing xmltype(transaction_document) columns location_id NUMBER path 'LocationId', organization_id NUMBER path 'OrganizationId', name NOT NULL VARCHAR2(100) path 'Name', creation_date VARCHAR2(15) path 'CreationDate',PeopleGroupId NUMBER path 'PeopleGroupId',REQUISITION_ID NUMBER(15)path 'RequisitionId',COMMENTS LONG() path 'Comments')
x
WHERE t.transaction_ref_table = 'PER_ALL_VACANCIES');following is error
Error at Command Line:2 Column:214
Error report:
SQL Error: ORA-00902: invalid datatype
00902. 00000 - "invalid datatype"
*Cause:
*Action:also it gives error when I takes data type as long() for column Comments
Error at Command Line:2 Column:392
Error report:
SQL Error: ORA-00907: missing right parenthesis
00907. 00000 - "missing right parenthesis"
*Cause:
*Action:LONG is not ( and never will be, so don't bother asking) supported by XMLTable. You should use CLOB or BLOB.
SQL> drop table HR_API_TRANSACTIONS
2 /
Table dropped.
SQL> drop table xx_PER_ALL_VACANCIES
2 /
Table dropped.
SQL> create table HR_API_TRANSACTIONS
2 (
3 TRANSACTION_REF_TABLE VARCHAR2(32),
4 TRANSACTION_DOCUMENT CLOB
5 )
6 /
Table created.
SQL> CREATE TABLE xx_PER_ALL_VACANCIES
2 AS
3 (
4 SELECT x.*
5 FROM hr_api_transactions t,
6 xmltable
7 (
8 '//PerAllVacanciesEORow'
9 passing xmltype(transaction_document)
10 columns location_id NUMBER path 'LocationId',
11 organization_id NUMBER path 'OrganizationId',
12 name VARCHAR2(100) path 'Name',
13 creation_date VARCHAR2(15) path 'CreationDate',
14 PeopleGroupId NUMBER path 'PeopleGroupId',
15 REQUISITION_ID NUMBER(15) path 'RequisitionId',
16 COMMENTS LONG() path 'Comments'
17 ) x
18 WHERE t.transaction_ref_table = 'PER_ALL_VACANCIES'
19 )
20 /
COMMENTS LONG() path 'Comments'
ERROR at line 16:
ORA-00907: missing right parenthesis
SQL> CREATE TABLE xx_PER_ALL_VACANCIES
2 AS
3 (
4 SELECT x.*
5 FROM hr_api_transactions t,
6 xmltable
7 (
8 '//PerAllVacanciesEORow'
9 passing xmltype(transaction_document)
10 columns location_id NUMBER path 'LocationId',
11 organization_id NUMBER path 'OrganizationId',
12 name VARCHAR2(100) path 'Name',
13 creation_date VARCHAR2(15) path 'CreationDate',
14 PeopleGroupId NUMBER path 'PeopleGroupId',
15 REQUISITION_ID NUMBER(15) path 'RequisitionId',
16 COMMENTS LONG path 'Comments'
17 ) x
18 WHERE t.transaction_ref_table = 'PER_ALL_VACANCIES'
19 )
20 /
ERROR at line 19:
ORA-00997: illegal use of LONG datatype
SQL> CREATE TABLE xx_PER_ALL_VACANCIES
2 AS
3 (
4 SELECT x.*
5 FROM hr_api_transactions t,
6 xmltable
7 (
8 '//PerAllVacanciesEORow'
9 passing xmltype(transaction_document)
10 columns location_id NUMBER path 'LocationId',
11 organization_id NUMBER path 'OrganizationId',
12 name VARCHAR2(100) path 'Name',
13 creation_date VARCHAR2(15) path 'CreationDate',
14 PeopleGroupId NUMBER path 'PeopleGroupId',
15 REQUISITION_ID NUMBER(15) path 'RequisitionId',
16 COMMENTS CLOB path 'Comments'
17 ) x
18 WHERE t.transaction_ref_table = 'PER_ALL_VACANCIES'
19 )
20 /
Table created.
SQL> -
Changing number of columns on master page, does not affect pages?
I create a master page. say three columns per spread.
I go to actual pages, flow my type in with the loaded cursor and holding the shift key... it works like a charm... text flows in the three colums, adding pages until the end of the manuscript...
Now I decide I don't like the three columns. I go to the master page and change to 4 columns via "margins and columns..." under LAYOUT menu
I go to the pages assuming that any change in a masterpage will translate to the pages... NOT!
If I go to to my first page, the type is still in three colums...
All other changes I make on the masterpage do translate to the pages... like say a color bar at the top, the size and font of the folios... BUT NOT if I change the number of columns???
Can anyone shed light on this?You MUST tick the Option for "Master Text Frame" when Creating a new document.
OR you MUST include a Text Frame with the number of Columns on the master page.
Copy the text to the clip board
Delete all page except page 1
remove the existing text frame.
Drag the Master A to the page 1
CTRL or CMD (MAC) click shift the text frame to break it from the master.
Now paste your text in here
Insert a new page
And click the Overload (red cross) button and connect it to the page 2 hodling down shift.
From memory - hope I got it right ! -
Composite Key in Toplink Mapping File - equivalent to Hibernate?
Hi,
I have a POJO TestEntity which refers to primary key TestEntityKey. In Hibernate mapping hbm file, we define the entry as:
<composite-id name="id" class="TestEntityKey">
<key-property name ="testEntityCode" column = "TEST_ENT_CODE" type = "string" />
</composite-id>
Please confirm how to create the composite id in Toplink means kindly help that how to map my id to key:
<opm:primary-key>
<opm:attribute-name>id</opm:attribute-name>
<opm:field table="TEST_ENTITY_B" name="TEST_ENT_CODE" xsi:type="opm:column"/>
</opm:primary-key>
Thanks!Hey.. Thanks!
I am clear about the concept about defining annotation based composite key. Also, I read in the documentation that I'll be needing to define as direct, aggregate or one-to-one. But, I am not able to define and run the same in the project mapping xml of toplink.
It would be great if you can share some sample code for defining the same. For e.g. in my mentioned example, there is TestEntity POJO having 'id' as the attribute which gets populated with the testEntityCode of the TestEntityKey POJO. Please suggest the same for the same:
<opm:primary-key>
<opm:attribute-name>id</opm:attribute-name>
<opm:field table="TEST_ENTITY_B" name="TEST_ENT_CODE" xsi:type="opm:column"/>
</opm:primary-key>
Thanks! -
File Content Conversion for Unequal Number of Columns
Hi,
Iam following this thread FCC for Unequal Number of Columns.
/people/jeyakumar.muthu2/blog/2005/11/29/file-content-conversion-for-unequal-number-of-columns
when iam doing ,iam getting an error
Conversion initialization failed: java.lang.Exception: java.lang.Exception: java.lang.Exception: Error(s) in XML conversion parameters found: Parameter 'TOTALSET.fieldFixedLengths' or 'TOTALSET.fieldSeparator' is missing Consistency check: no. of arguments in 'TOTALSET.fieldFixedLength' does not match 'TOTALSET.fieldNames' (0 <> 1)
My conversion parameters are
Recordset Structure : TOTALSET,*
TOTALSET.fieldNames : ITEMSET
ignoreRecordsetName : true
TOTALSET.fieldSeparator : 'nl'
My file structure is as below
01,021000021,G4886704,080919,0742,001,,,2
02,G4886704,021000021,1,080918,0742,,2
03,000000135073477,,010,105303839,,,015,489113155,,,045,489039455,,,072,73700
Please help in resoving the error.
Thanks in Advance
SrinivasHi Srivinas,
your file structure is as below
01,021000021,G4886704,080919,0742,001,,,2
02,G4886704,021000021,1,080918,0742,,2
03,000000135073477,,010,105303839,,,015,489113155,,,045,489039455,,,072,73700
So it's easy, you have to use KEYFIELD option, coz you have something like that :
Line 1 : keyfield = 01 following by a limited number of columns (e.g 30 fields for Structure1)
Line 2 : keyfield = 02 following by a limited number of columns (e.g 14 fields for Structure2)
Line 3 : keyfield = 03 following by a limited number of columns (e.g 23 fields for Structure3)
Thanks to the Keyfield, you define a field which is present in each line that you can used to distinguished the different structures of lines. In your case, it seems that the keyfield is the first column (01, 02, 03).
Try to use that:
Recorset = TOTALSET (and don't use option "ignoreRecordsetName : true")
Recordset structure =Structure1,1,Structure2,(star),Structure3,(start) (the difficulty will be to find the good use of "*" and "1", but after some tests you will find the good one).
Note: replace (start) by the character " * "
Key field value = keyfield
Key field type = String (case sensitive)
Structure1.fieldNames = keyfield,field2, field3 etc.. of Structure1
Structure2.fieldNames = keyfield,field2, field3 etc.. of Structure2
Structure3.fieldNames = keyfield,field2, field3 etc.. of Structure3
and then you will have a XML like that:
TOTALSET
Structure1 and all its fieldN
Structure2 and all its fieldN
Structure2 and all its fieldN
Structure3 and all its fieldN
Structure3 and all its fieldN
TOTALSET
Structure1 and all its fieldN because I used Structure1,1
Structure3 and all its fieldN
Regards.
Mickael
Edited by: Mickael Huchet on Apr 20, 2009 5:18 PM
Edited by: Mickael Huchet on Apr 20, 2009 5:19 PM -
UiXML tables - variable number of columns?
I'm trying to define a <table> in a UIX page which will be generated from a set of parameters. This set of parameters will result in a varying number of columns so I'm looking at providing a DataObjectList which has DataObjects with keys for each of the columns attributes (header text, name of control, value of control etc.). I want to do something similar to <contents data:childData=...> on the <table> contents but this doesn't seem to work. It seems that <table> needs you to know how many columns will be present - is that so or is there some way I can do this?
Cheers
IanIan,
That is correct, the uiMXL <table> element cannot currently support
a variable number of columns (using something akin to the
childData support in other contexts). But there are two approaches
to get what you want.
If you know the range of possible columns, then you can add a <column>
element for each possible column in the <table>'s contents and then
databind the rendered flag of the column element to hide/show the
column as necessary.
However, the real solution to your scenario, where the number of columns
is completely unknown when you're designing the page, is our canonical
example of a time you should write Java code for a portion of your page.
Specifically, you can use the XML <include> element to refer to a
DataProvider that will programatically create a TableBean. This
technique is discussed in the Dynamic Structure for UIX pages
portion of the UIX Developer's Guide. -
Setting composite key in Container Managed Entity Bean
In my database table i set primary key to two columns making them as composite key. how do i set that in my container managed entity bean home interface findByPrimaryKey() method and in deployment descriptor file.
1. create another class (say CompositePK) that will embed the two fields keyA and keyB corresponding to the two pk of your table (declare them public) .
2. in your Bean declare keyA and keyB public.
3. in the dd declare your bean primary-key-class as CompositePK and the primary-key-field as keyA and keyB.
this is the method i use (with BAS) even if the key is simple (such as Integer). -
How to generate report with dynamic variable number of columns?
How to generate report with dynamic variable number of columns?
I need to generate a report with varying column names (state names) as follows:
SELECT AK, AL, AR,... FROM States ;
I get these column names from the result of another query.
In order to clarify my question, Please consider following table:
CREATE TABLE TIME_PERIODS (
PERIOD VARCHAR2 (50) PRIMARY KEY
CREATE TABLE STATE_INCOME (
NAME VARCHAR2 (2),
PERIOD VARCHAR2 (50) REFERENCES TIME_PERIODS (PERIOD) ,
INCOME NUMBER (12, 2)
I like to generate a report as follows:
AK CA DE FL ...
PERIOD1 1222.23 2423.20 232.33 345.21
PERIOD2
PERIOD3
Total 433242.23 56744.34 8872.21 2324.23 ...
The TIME_PERIODS.Period and State.Name could change dynamically.
So I can't specify the state name in Select query like
SELECT AK, AL, AR,... FROM
What is the best way to generate this report?SQL> -- test tables and test data:
SQL> CREATE TABLE states
2 (state VARCHAR2 (2))
3 /
Table created.
SQL> INSERT INTO states
2 VALUES ('AK')
3 /
1 row created.
SQL> INSERT INTO states
2 VALUES ('AL')
3 /
1 row created.
SQL> INSERT INTO states
2 VALUES ('AR')
3 /
1 row created.
SQL> INSERT INTO states
2 VALUES ('CA')
3 /
1 row created.
SQL> INSERT INTO states
2 VALUES ('DE')
3 /
1 row created.
SQL> INSERT INTO states
2 VALUES ('FL')
3 /
1 row created.
SQL> CREATE TABLE TIME_PERIODS
2 (PERIOD VARCHAR2 (50) PRIMARY KEY)
3 /
Table created.
SQL> INSERT INTO time_periods
2 VALUES ('PERIOD1')
3 /
1 row created.
SQL> INSERT INTO time_periods
2 VALUES ('PERIOD2')
3 /
1 row created.
SQL> INSERT INTO time_periods
2 VALUES ('PERIOD3')
3 /
1 row created.
SQL> INSERT INTO time_periods
2 VALUES ('PERIOD4')
3 /
1 row created.
SQL> CREATE TABLE STATE_INCOME
2 (NAME VARCHAR2 (2),
3 PERIOD VARCHAR2 (50) REFERENCES TIME_PERIODS (PERIOD),
4 INCOME NUMBER (12, 2))
5 /
Table created.
SQL> INSERT INTO state_income
2 VALUES ('AK', 'PERIOD1', 1222.23)
3 /
1 row created.
SQL> INSERT INTO state_income
2 VALUES ('CA', 'PERIOD1', 2423.20)
3 /
1 row created.
SQL> INSERT INTO state_income
2 VALUES ('DE', 'PERIOD1', 232.33)
3 /
1 row created.
SQL> INSERT INTO state_income
2 VALUES ('FL', 'PERIOD1', 345.21)
3 /
1 row created.
SQL> -- the basic query:
SQL> SELECT SUBSTR (time_periods.period, 1, 10) period,
2 SUM (DECODE (name, 'AK', income)) "AK",
3 SUM (DECODE (name, 'CA', income)) "CA",
4 SUM (DECODE (name, 'DE', income)) "DE",
5 SUM (DECODE (name, 'FL', income)) "FL"
6 FROM state_income, time_periods
7 WHERE time_periods.period = state_income.period (+)
8 AND time_periods.period IN ('PERIOD1','PERIOD2','PERIOD3')
9 GROUP BY ROLLUP (time_periods.period)
10 /
PERIOD AK CA DE FL
PERIOD1 1222.23 2423.2 232.33 345.21
PERIOD2
PERIOD3
1222.23 2423.2 232.33 345.21
SQL> -- package that dynamically executes the query
SQL> -- given variable numbers and values
SQL> -- of states and periods:
SQL> CREATE OR REPLACE PACKAGE package_name
2 AS
3 TYPE cursor_type IS REF CURSOR;
4 PROCEDURE procedure_name
5 (p_periods IN VARCHAR2,
6 p_states IN VARCHAR2,
7 cursor_name IN OUT cursor_type);
8 END package_name;
9 /
Package created.
SQL> CREATE OR REPLACE PACKAGE BODY package_name
2 AS
3 PROCEDURE procedure_name
4 (p_periods IN VARCHAR2,
5 p_states IN VARCHAR2,
6 cursor_name IN OUT cursor_type)
7 IS
8 v_periods VARCHAR2 (1000);
9 v_sql VARCHAR2 (4000);
10 v_states VARCHAR2 (1000) := p_states;
11 BEGIN
12 v_periods := REPLACE (p_periods, ',', ''',''');
13 v_sql := 'SELECT SUBSTR(time_periods.period,1,10) period';
14 WHILE LENGTH (v_states) > 1
15 LOOP
16 v_sql := v_sql
17 || ',SUM(DECODE(name,'''
18 || SUBSTR (v_states,1,2) || ''',income)) "' || SUBSTR (v_states,1,2)
19 || '"';
20 v_states := LTRIM (SUBSTR (v_states, 3), ',');
21 END LOOP;
22 v_sql := v_sql
23 || 'FROM state_income, time_periods
24 WHERE time_periods.period = state_income.period (+)
25 AND time_periods.period IN (''' || v_periods || ''')
26 GROUP BY ROLLUP (time_periods.period)';
27 OPEN cursor_name FOR v_sql;
28 END procedure_name;
29 END package_name;
30 /
Package body created.
SQL> -- sample executions from SQL:
SQL> VARIABLE g_ref REFCURSOR
SQL> EXEC package_name.procedure_name ('PERIOD1,PERIOD2,PERIOD3','AK,CA,DE,FL', :g_ref)
PL/SQL procedure successfully completed.
SQL> PRINT g_ref
PERIOD AK CA DE FL
PERIOD1 1222.23 2423.2 232.33 345.21
PERIOD2
PERIOD3
1222.23 2423.2 232.33 345.21
SQL> EXEC package_name.procedure_name ('PERIOD1,PERIOD2','AK,AL,AR', :g_ref)
PL/SQL procedure successfully completed.
SQL> PRINT g_ref
PERIOD AK AL AR
PERIOD1 1222.23
PERIOD2
1222.23
SQL> -- sample execution from PL/SQL block
SQL> -- using parameters derived from processing
SQL> -- cursors containing results of other queries:
SQL> DECLARE
2 CURSOR c_period
3 IS
4 SELECT period
5 FROM time_periods;
6 v_periods VARCHAR2 (1000);
7 v_delimiter VARCHAR2 (1) := NULL;
8 CURSOR c_states
9 IS
10 SELECT state
11 FROM states;
12 v_states VARCHAR2 (1000);
13 BEGIN
14 FOR r_period IN c_period
15 LOOP
16 v_periods := v_periods || v_delimiter || r_period.period;
17 v_delimiter := ',';
18 END LOOP;
19 v_delimiter := NULL;
20 FOR r_states IN c_states
21 LOOP
22 v_states := v_states || v_delimiter || r_states.state;
23 v_delimiter := ',';
24 END LOOP;
25 package_name.procedure_name (v_periods, v_states, :g_ref);
26 END;
27 /
PL/SQL procedure successfully completed.
SQL> PRINT g_ref
PERIOD AK AL AR CA DE FL
PERIOD1 1222.23 2423.2 232.33 345.21
PERIOD2
PERIOD3
PERIOD4
1222.23 2423.2 232.33 345.21 -
Hi experts.
I have a small query.
Is there any performance impact of having a date field along with four other fields as part of a composite key.When you add an index, there is definitely some overhead to get the index synchronized with newly added/updated data (so whether you have indexed NUMBER, CHARs or DATEs does not matter - but I could be wrong in saying this).
Concerning your SELECTs, if your existing queries were using this index then they may or may not use the new index (due to cardinality and other factors); so you need to test this first.
Maybe you are looking for
-
Hi, this is the first time I've posted here so I hope I'm not in the wrong spot. I recently built my first PC running windows 7, MSI Z97 Gaming 7 - my video Card is a MSI GTX970 Twin Frozen V. I removed the graphics card to do some cleaning and when
-
How can I put Service charge to receive money from customer in Sales Return
My company will receive the Restocking fee from customer when customer want to return the goods. I create a Sales Return Document for sales return but I can't put the service charge to charge my customer in the sales return document. If there is any
-
imageshack.com/i/0e8s53p
-
Business area and profit center
plz can anyone explain me what is the diffrence between business area and profit center.
-
Hi, my mac started itself to lose ethernet connection when i go away for 10 mins or more. When i come back it gets connection if i move the mouse only. I can't find where to set options or how to fix this issue. Can you help me please ? thx