Extended stats partial implementation (multi-column stats) in 10.2.0.4

Hi everyone,
I saw a note today on ML, which says that new 11g's feature - [Extended statistics|http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/stats.htm#sthref1177] - is partially available in 10.2.0.4. See [Bug #5040753 Optimal index is not picked on simple query / Column group statistics|https://metalink2.oracle.com/metalink/plsql/f?p=130:14:3330964537507892972::::p14_database_id,p14_docid,p14_show_header,p14_show_help,p14_black_frame,p14_font:NOT,5040753.8,1,0,1,helvetica] for details. The note suggests to turn on this feature using fixcontrol, but it does not say how actually to employ it. Because dbms_stats.create_extended_stats function is not available in 10.2.0.4, I'm curious how it is actually supposed to work in 10.2.0.4? I wrote a simple test:
drop table t cascade constraints purge;
create table t as select rownum id, mod(rownum, 100) x, mod(rownum, 100) y from dual connect by level <= 100000;
exec dbms_stats.gather_table_stats(user, 't');
explain plan for select * from t where x = :1 and y = :2;
select * from table(dbms_xplan.display);
disc
conn tim/t
drop table t cascade constraints purge;
create table t as select rownum id, mod(rownum, 100) x, mod(rownum, 100) y from dual connect by level <= 100000;
exec dbms_stats.gather_table_stats(user, 't');
alter session set "_fix_control"='5765456:7';
explain plan for select * from t where x = :1 and y = :2;
select * from table(dbms_xplan.display);
disc
conn tim/t
drop table t cascade constraints purge;
create table t as select rownum id, mod(rownum, 100) x, mod(rownum, 100) y from dual connect by level <= 100000;
alter session set "_fix_control"='5765456:7';
exec dbms_stats.gather_table_stats(user, 't');
explain plan for select * from t where x = :1 and y = :2;
select * from table(dbms_xplan.display);In alll cases cardinality estimate was 10, as usually without extended statistics:
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT  |      |    10 |   100 |    53   (6)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| T    |    10 |   100 |    53   (6)| 00:00:01 |
Predicate Information (identified by operation id):
   1 - filter("X"=TO_NUMBER(:1) AND "Y"=TO_NUMBER(:2))10053 trace confirmed that fix is enabled and considered by CBO:
PARAMETERS USED BY THE OPTIMIZER
  PARAMETERS WITH ALTERED VALUES
  optimizer_secure_view_merging       = false
  _optimizer_connect_by_cost_based    = false
  _fix_control_key                    = -113
  Bug Fix Control Environment
  fix  5765456 = 7        *
...But calculations were typical:
BASE STATISTICAL INFORMATION
Table Stats::
  Table:  T  Alias:  T
    #Rows: 100000  #Blks:  220  AvgRowLen:  10.00
SINGLE TABLE ACCESS PATH
  BEGIN Single Table Cardinality Estimation
  Column (#2): X(NUMBER)
    AvgLen: 3.00 NDV: 101 Nulls: 0 Density: 0.009901 Min: 0 Max: 99
  Column (#3): Y(NUMBER)
    AvgLen: 3.00 NDV: 101 Nulls: 0 Density: 0.009901 Min: 0 Max: 99
  Table:  T  Alias: T    
    Card: Original: 100000  Rounded: 10  Computed: 9.80  Non Adjusted: 9.80
  END   Single Table Cardinality Estimation
  Access Path: TableScan
    Cost:  53.19  Resp: 53.19  Degree: 0
      Cost_io: 50.00  Cost_cpu: 35715232
      Resp_io: 50.00  Resp_cpu: 35715232
  Best:: AccessPath: TableScan
         Cost: 53.19  Degree: 1  Resp: 53.19  Card: 9.80  Bytes: 0Any thoughts?

Jonathan,
thanks for stopping by. Yes, forcing INDEX access with a hint, disabled fix for bug and more correctly gathered statistics shows INDEX access cardinality 1000:
SQL> alter session set "_fix_control"='5765456:0';
Session altered
SQL> exec dbms_stats.gather_table_stats(user, 't', estimate_percent=>null,method_opt=>'for all columns size 1', cascade=>true);
PL/SQL procedure successfully completed
SQL> explain plan for select /*+ index(t t_indx) */ * from t where x = :1 and y = :2;
Explained
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 4155885868
| Id  | Operation                   | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT            |        |    10 |   100 |   223   (0)| 00:00:03 |
|   1 |  TABLE ACCESS BY INDEX ROWID| T      |    10 |   100 |   223   (0)| 00:00:03 |
|*  2 |   INDEX RANGE SCAN          | T_INDX |  1000 |       |     3   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   2 - access("X"=TO_NUMBER(:1) AND "Y"=TO_NUMBER(:2))but it still isn't correct for TABLE ACCESS. With default statistics gathering settings dbms_stats gathered FREQUENCY histogram on both X & Y columns and computations for cardinality estimates were not correct:
SQL> alter session set "_fix_control"='5765456:0';
Session altered
SQL> exec dbms_stats.gather_table_stats(user, 't', cascade=>true);
PL/SQL procedure successfully completed
SQL> explain plan for select /*+ index(t t_indx) */ * from t where x = :1 and y = :2;
Explained
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 4155885868
| Id  | Operation                   | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT            |        |    10 |   100 |     4   (0)| 00:00:01 |
|   1 |  TABLE ACCESS BY INDEX ROWID| T      |    10 |   100 |     4   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN          | T_INDX |    10 |       |     1   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   2 - access("X"=TO_NUMBER(:1) AND "Y"=TO_NUMBER(:2))I believe this happens due to CBO computes INDEX selectivity using different formula for that case:
BASE STATISTICAL INFORMATION
Table Stats::
  Table:  T  Alias:  T
    #Rows: 100000  #Blks:  220  AvgRowLen:  10.00
Index Stats::
  Index: T_INDX  Col#: 2 3
    LVLS: 1  #LB: 237  #DK: 100  LB/K: 2.00  DB/K: 220.00  CLUF: 22000.00
    User hint to use this index
SINGLE TABLE ACCESS PATH
  BEGIN Single Table Cardinality Estimation
  Column (#2): X(NUMBER)
    AvgLen: 3.00 NDV: 100 Nulls: 0 Density: 0.003424 Min: 0 Max: 99
    Histogram: Freq  #Bkts: 100  UncompBkts: 5403  EndPtVals: 100
  Column (#3): Y(NUMBER)
    AvgLen: 3.00 NDV: 100 Nulls: 0 Density: 0.003424 Min: 0 Max: 99
    Histogram: Freq  #Bkts: 100  UncompBkts: 5403  EndPtVals: 100
  Table:  T  Alias: T    
    Card: Original: 100000  Rounded: 10  Computed: 10.00  Non Adjusted: 10.00
  END   Single Table Cardinality Estimation
  Access Path: index (AllEqRange)
    Index: T_INDX
    resc_io: 4.00  resc_cpu: 33236
    ix_sel: 1.0000e-004  ix_sel_with_filters: 1.0000e-004
    Cost: 4.00  Resp: 4.00  Degree: 1
  Best:: AccessPath: IndexRange  Index: T_INDX
         Cost: 4.00  Degree: 1  Resp: 4.00  Card: 10.00  Bytes: 0To give a complete picture, this is 10053 excerpt for "normal stats" + disabled bug fix + forced index:
  BEGIN Single Table Cardinality Estimation
  Column (#2): X(NUMBER)
    AvgLen: 3.00 NDV: 100 Nulls: 0 Density: 0.01 Min: 0 Max: 99
  Column (#3): Y(NUMBER)
    AvgLen: 3.00 NDV: 100 Nulls: 0 Density: 0.01 Min: 0 Max: 99
  Table:  T  Alias: T    
    Card: Original: 100000  Rounded: 10  Computed: 10.00  Non Adjusted: 10.00
  END   Single Table Cardinality Estimation
  Access Path: index (AllEqRange)
    Index: T_INDX
    resc_io: 223.00  resc_cpu: 1978931
    ix_sel: 0.01  ix_sel_with_filters: 0.01
    Cost: 223.18  Resp: 223.18  Degree: 1
  Best:: AccessPath: IndexRange  Index: T_INDX
         Cost: 223.18  Degree: 1  Resp: 223.18  Card: 10.00  Bytes: 0And this one for "normal stats" + enabled bug fix:
  BEGIN Single Table Cardinality Estimation
  Column (#2): X(NUMBER)
    AvgLen: 3.00 NDV: 100 Nulls: 0 Density: 0.01 Min: 0 Max: 99
  Column (#3): Y(NUMBER)
    AvgLen: 3.00 NDV: 100 Nulls: 0 Density: 0.01 Min: 0 Max: 99
  ColGroup (#1, Index) T_INDX
    Col#: 2 3    CorStregth: 100.00
  ColGroup Usage:: PredCnt: 2  Matches Full: #0  Partial:  Sel: 0.0100
  Table:  T  Alias: T    
    Card: Original: 100000  Rounded: 1000  Computed: 1000.00  Non Adjusted: 1000.00
  END   Single Table Cardinality Estimation
  ColGroup Usage:: PredCnt: 2  Matches Full: #0  Partial:  Sel: 0.0100
  ColGroup Usage:: PredCnt: 2  Matches Full: #0  Partial:  Sel: 0.0100
  Access Path: index (AllEqRange)
    Index: T_INDX
    resc_io: 223.00  resc_cpu: 1978931
    ix_sel: 0.01  ix_sel_with_filters: 0.01
    Cost: 223.18  Resp: 223.18  Degree: 1
  Best:: AccessPath: IndexRange  Index: T_INDX
         Cost: 223.18  Degree: 1  Resp: 223.18  Card: 1000.00  Bytes: 0Tests were performed on the same machine (10.2.0.4).

Similar Messages

  • Bug 2679062 - Wrong results possible from multi-column INLIST - though stat

    Hi,
    The following test case is supplied in the metalink in bug no. 2871341, the base bug for this bug is 2679062.
    REPRODUCIBILITY:
    Reproduces constantly with simple test case below:
    TEST CASE:
    DROP TABLE A1
    CREATE TABLE A1 (X1 VARCHAR2(10), X2 VARCHAR2(10))
    REM *********** Create the second table: ***************
    DROP TABLE A2
    CREATE TABLE A2 (X1 VARCHAR2(10), X2 VARCHAR2(10))
    INSERT INTO A1 VALUES ('1','2');
    INSERT INTO A2 VALUES ('3','4');
    COMMIT;
    CREATE INDEX A1_X1 ON A1(X1 );
    CREATE INDEX A1_X2 ON A1(X2);
    CREATE INDEX A2_X1 ON A2(X1);
    CREATE INDEX A2_X2 ON A2(X2);
    CREATE OR REPLACE VIEW A_ALL AS SELECT * FROM A1 UNION ALL SELECT * FROM A2;
    ANALYZE TABLE A1 COMPUTE STATISTICS;
    ANALYZE TABLE A2 COMPUTE STATISTICS;
    SELECT * FROM A_ALL;
    SELECT * FROM A_ALL WHERE (X1='1' AND X2='2') ;
    SELECT * FROM A_ALL WHERE ((X1='1' AND X2='2') OR (X1='3' AND X2='4'));
    The 2nd query returns answer while the second is not !
    The following is published in the 9.2.0.4 fixed bug list:
    " 9204 - 2679062 - Wrong results possible from multi-column INLIST "
    I have installed 9.2.0.4 patch set on a win 2000 machine Oracle and saw that the above case is actually solved but our application which has a very similar case doesn't.
    After investigating I found the following test case that fails, it reproduces only when you have index on all columns (covering index):
    drop table t1_1;
    drop table t1_2;
    create table t1_1(c1 number, c2 number, c3 number);
    create table t1_2(c1 number, c2 number, c3 number);
    create index t1_1_ix on t1_1(c1, c2, c3);
    create index t1_2_ix on t1_2(c1, c2, c3);
    create or replace view t1 as select * from t1_1 union all select * from t1_2;
    insert into t1_1 values(1, 2, 100);
    insert into t1_2 values(1, 2, 200);
    commit;
    analyze table t1_1 compute statistics;
    analyze table t1_2 compute statistics;
    prompt
    prompt #######################################
    prompt try 1 - works fine
    prompt #######################################
    prompt
    select * from t1
    where
    (c1=1)
    and
    ( (c2=2) and (c3=100)
    prompt
    prompt #######################################
    prompt try 2 - works fine
    prompt #######################################
    prompt
    select * from t1
    where
    (c1=1)
    and
    (c2=2) and (c3=200)
    prompt
    prompt #######################################
    prompt try 3 - try 1 OR try 2 does not work !
    prompt #######################################
    prompt
    select * from t1
    where
    (c1=1)
    and
    ( ( (c2=2) and (c3=100) )
    or
    ( (c2=2) and (c3=200) )
    opened a TAR and wanted to share with you.
    Tal Olier ([email protected]).

    Hi,
    The following test case is supplied in the metalink in bug no. 2871341, the base bug for this bug is 2679062.
    REPRODUCIBILITY:
    Reproduces constantly with simple test case below:
    TEST CASE:
    DROP TABLE A1
    CREATE TABLE A1 (X1 VARCHAR2(10), X2 VARCHAR2(10))
    REM *********** Create the second table: ***************
    DROP TABLE A2
    CREATE TABLE A2 (X1 VARCHAR2(10), X2 VARCHAR2(10))
    INSERT INTO A1 VALUES ('1','2');
    INSERT INTO A2 VALUES ('3','4');
    COMMIT;
    CREATE INDEX A1_X1 ON A1(X1 );
    CREATE INDEX A1_X2 ON A1(X2);
    CREATE INDEX A2_X1 ON A2(X1);
    CREATE INDEX A2_X2 ON A2(X2);
    CREATE OR REPLACE VIEW A_ALL AS SELECT * FROM A1 UNION ALL SELECT * FROM A2;
    ANALYZE TABLE A1 COMPUTE STATISTICS;
    ANALYZE TABLE A2 COMPUTE STATISTICS;
    SELECT * FROM A_ALL;
    SELECT * FROM A_ALL WHERE (X1='1' AND X2='2') ;
    SELECT * FROM A_ALL WHERE ((X1='1' AND X2='2') OR (X1='3' AND X2='4'));
    The 2nd query returns answer while the second is not !
    The following is published in the 9.2.0.4 fixed bug list:
    " 9204 - 2679062 - Wrong results possible from multi-column INLIST "
    I have installed 9.2.0.4 patch set on a win 2000 machine Oracle and saw that the above case is actually solved but our application which has a very similar case doesn't.
    After investigating I found the following test case that fails, it reproduces only when you have index on all columns (covering index):
    drop table t1_1;
    drop table t1_2;
    create table t1_1(c1 number, c2 number, c3 number);
    create table t1_2(c1 number, c2 number, c3 number);
    create index t1_1_ix on t1_1(c1, c2, c3);
    create index t1_2_ix on t1_2(c1, c2, c3);
    create or replace view t1 as select * from t1_1 union all select * from t1_2;
    insert into t1_1 values(1, 2, 100);
    insert into t1_2 values(1, 2, 200);
    commit;
    analyze table t1_1 compute statistics;
    analyze table t1_2 compute statistics;
    prompt
    prompt #######################################
    prompt try 1 - works fine
    prompt #######################################
    prompt
    select * from t1
    where
    (c1=1)
    and
    ( (c2=2) and (c3=100)
    prompt
    prompt #######################################
    prompt try 2 - works fine
    prompt #######################################
    prompt
    select * from t1
    where
    (c1=1)
    and
    (c2=2) and (c3=200)
    prompt
    prompt #######################################
    prompt try 3 - try 1 OR try 2 does not work !
    prompt #######################################
    prompt
    select * from t1
    where
    (c1=1)
    and
    ( ( (c2=2) and (c3=100) )
    or
    ( (c2=2) and (c3=200) )
    opened a TAR and wanted to share with you.
    Tal Olier ([email protected]).

  • How to write a case statement for the totals column of two different years (2013 and 2014) of the same month so that I can get a +/- column

    Please Help!!!
    How to write a case statement for the totals column of two different years (2013 and 2014) of the same month so that I can get a +/- column.
                                      January 2014         January
    2013                            +/-
                    Region   Entry   Exit  Total    Entry   Exit   Total   (Total of Jan2014-Total of Jan2013)
                    A               2         3      
    40        5       7        30                    40-30= 10

    What is a table structure? Sorry cannot test it right now..
    SELECT <columns>,(SELECT Total FROM tbl WHERE Y=2014)-(SELECT Total FROM tbl WHERE Y=2013)
    FROM tbl
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • SSIS: Using CASE Statement Within A Derived Column Transformation Expression

    The following is my Data Flow:
    Ole DB Source > Copy Column > Derived Column >Ole DB Command
    My OLE DB Source has the following SQL command task:
    SELECT *
    FROM Repair R
    LEFT OUTER JOIN Vehicle V
    ON R.SN = V.SN
    AND R.Reg = V.Reg
    LEFT OUTER JOIN Product P
    ON R.PID = P.PID
    This yields a column of concern for me named PartNumber, which are represented by the following 2 formats:
    The following are my Copied Columns:
    Input Column = PartNumber
    Output Alias = Copy of PartNumber
    The following are my Derived Column expressions:
    Derived Column Name Derived Column Expression
    Name Replace 'PartNumber' LEFT(PartNumber,FINDSTRING(PartNumber,"-",1) - 1)
    Copy of Name Replace 'Copy of PartNumber' RIGHT([Copy of PartNumber],LEN([Copy of PartNumber]) - FINDSTRING([Copy of PartNumber],"-",1))
    So My PartNumber Column is Replaced with ######### of type
    string and the Copy of PartNumber column is replaced with
    #### of type int
    As I stated earlier PartNumber also is in the format of %-%-% which raises the following question:
    How can I replace PartNumber Column with NULL if in format of
    %-%-% and take the PartNumber and put it in new column named
    SubPart while keeping all the logic within SSIS objects?
    So in essence I want to do something like the following:
    PartNumber = CASE
    WHEN 'PartNumber' LIKE '%-%-%'
    THEN ABC = PartNumber AND PartNumber IS NULL
    END
    I have tried the case statement in a Derived Column expression and is not working. Would I add the
    CASE statement to the SQL command task in my OLE DB Source?
    I hope this question is concise for you.

    If it must be in SSIS, I would put a derived column stage earlier in the process to do my check for me. Then in the second derived column stage do the check against each output column (part, subpart, copy of part) to decide which way it goes
    PS Not sure if it's a 2012 function but SSIS has a function called TOKEN that will allow you to pull your subparts for you rather than the left/right you are doing

  • SQL script(column statement) understanding

    hi,
    i am ataching the code of one of the SQL scripts. I am having problem in understanding some of the lines of the code for which i have put a comment, the lines start with the "column" statement and the spool statements. Please help in solving my query.
    regards,
    jatin
    SET LINESIZE 200
    SET PAGESIZE 10000
    --Problem in understanding below 4 lines
    column spool_text_source new_value spool_text
    select 'c:\temp\DAR_' || to_char(sysdate,'YYYYMMDD')
    spool_text_source from dual;
    spool &spool_text..txt
    --query starts here 
    SELECT DISTINCT E.CITY_CODE,A.MOBILE_NO,A.ITEM_TYPE_ID,B.DOCUMENT_NUM,B.DOCUMENT_DT,E.DISTRIBUTOR_NAME
    FROM
    INV_SIM_SERIAL A,INVOICE_HEADER B,INVOICE_DETAIL C,INV_SIM_SERIAL D,DISTRIBUTOR_MASTER E WHERE
    A.DOC_LINE_ID=C.DOC_LINE_ID AND
    B.DOCUMENT_NUM=C.DOCUMENT_NUM AND
    A.SERIAL_ID=NVL(D.OLD_SERIAL_ID,D.SERIAL_ID) AND
    (trunc(A.FIRST_CALL_DT) = trunc(sysdate-1) OR trunc(D.FIRST_CALL_DT)= trunc(sysdate-1)) AND
    NVL(A.OLD_DISTRIBUTOR_ID,A.DISTRIBUTOR_ID)=E.DISTRIBUTOR_ID AND A.ACTIVATE_DT IS NULL
    order by e.distributor_name;
    --query ends here
    spool off
    exit

    Hi
    The part
    column spool_text_source new_value spool_text
    select 'c:\temp\DAR_' || to_char(sysdate,'YYYYMMDD')
    spool_text_source from dual;
    spool &spool_text..txt can be written as
    column spool_text_source new_value spool_text
    select 'c:\temp\DAR_' || to_char(sysdate,'YYYYMMDD') spool_text_source from dual;
    spool &spool_text..txt line 2 and 3 are just one sql-statement
    but back to what it does
    line 1 column ...
    it tells SQL*Plus to get the result from the column spool_test_source of next sql-statement and put into the spool_text variable.
    line 2 the SQL-statment it actuallt create an file name for the spool file and the result is put into the spool_text variable.
    line 3 open the spool file and start spooling output from the script.

  • Determine the best width for ListCellRenderer - Multi-column combo box

    Currently, I am having a multi column combo box. In order for the column to align properly during show popup, I use box layout to do so. However, the short coming for box layout is that, the size for each column is fixed. This makes me have a difficulty, when I have a long string to be displayed. The problem is shown through the following screen shoot.
    http://i.imgur.com/4Nfc6.png
    This is because in 2nd column,
    1) All the 3 rows must be in same size so that they are aligned.
    2) But 1st row and 2nd row cell renderer, do not know 3rd row is holding such a long string.
    The code (2 files) to demo this problem is as follow. Is there any way the size of the cell will be adjusted automatically? Yet, all the row will be aligned properly.
    ResultSetCellRenderer.java
    package javaapplication24;
    import java.awt.Color;
    import java.awt.Component;
    import javaapplication24.NewJFrame.ResultType;
    import javax.swing.JList;
    import javax.swing.ListCellRenderer;
    import javax.swing.UIManager;
    * @author yccheok
    public class ResultSetCellRenderer extends javax.swing.JPanel implements ListCellRenderer {
        /** Creates new form ResultSetCellRenderer */
        public ResultSetCellRenderer() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.X_AXIS));
            jLabel1.setText("jLabel1");
            jLabel1.setMaximumSize(new java.awt.Dimension(88, 14));
            jLabel1.setMinimumSize(new java.awt.Dimension(88, 14));
            jLabel1.setPreferredSize(new java.awt.Dimension(88, 14));
            add(jLabel1);
            jLabel2.setText("jLabel2");
            jLabel2.setMaximumSize(new java.awt.Dimension(100, 14));
            jLabel2.setMinimumSize(new java.awt.Dimension(200, 14));
            jLabel2.setPreferredSize(new java.awt.Dimension(100, 14));
            add(jLabel2);
        }// </editor-fold>
        // Variables declaration - do not modify
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        // End of variables declaration
        // Do not use static, so that our on-the-fly look n feel change will work.
        private final Color cfc  = UIManager.getColor("ComboBox.foreground");
        private final Color cbc  = UIManager.getColor("ComboBox.background");
        private final Color csfc = UIManager.getColor("ComboBox.selectionForeground");
        private final Color csbc = UIManager.getColor("ComboBox.selectionBackground");
        private final Color cdfc = UIManager.getColor("ComboBox.disabledForeground");
        // For Nimbus look n feel.
        private final Color nimbus_csfc;
             Color c = UIManager.getColor("ComboBox:\"ComboBox.renderer\"[Selected].textForeground");
             // Pretty interesting. Applying "c" directly on the component will not
             // work. I have the create a new instance of Color based on "c" to make
             // it works.
             nimbus_csfc = c != null ? new Color(c.getRed(), c.getGreen(), c.getBlue()) : null;
        private final Color nimbus_csbc;
            Color c = UIManager.getColor("ComboBox:\"ComboBox.renderer\"[Selected].background");
             // Pretty interesting. Applying "c" directly on the component will not
             // work. I have the create a new instance of Color based on "c" to make
             // it works.
            nimbus_csbc = c != null ? new Color(c.getRed(), c.getGreen(), c.getBlue()) : null;
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            final Color _csbc = csbc != null ? csbc : nimbus_csbc;
            final Color _csfc = csfc != null ? csfc : nimbus_csfc;
            this.setBackground(isSelected ? _csbc : cbc);
            this.setForeground(isSelected ? _csfc : cfc);
            jLabel1.setBackground(isSelected ? _csbc : cbc);
            jLabel1.setForeground(isSelected ? _csfc : cfc);
            jLabel2.setBackground(isSelected ? _csbc : cbc);
            jLabel2.setForeground(isSelected ? _csfc : cfc);
            final ResultType result = (ResultType)value;
            jLabel1.setText(result.symbol);
            jLabel2.setText(result.name);
            return this;
    NewJFrame.java
    package javaapplication24;
    import java.awt.Container;
    import java.awt.Dimension;
    import javax.swing.JComboBox;
    import javax.swing.JList;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    import javax.swing.event.PopupMenuEvent;
    import javax.swing.event.PopupMenuListener;
    import javax.swing.plaf.basic.BasicComboPopup;
    * @author yccheok
    public class NewJFrame extends javax.swing.JFrame {
        public static class ResultType {
             * The symbol.
            public final String symbol;
             * The name.
            public final String name;
            public ResultType(String symbol, String name) {
                this.symbol = symbol;
                this.name = name;
            @Override
            public String toString() {
                return symbol;
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
            this.jComboBox1.addPopupMenuListener(this.getPopupMenuListener());
            this.jComboBox1.setRenderer(new ResultSetCellRenderer());
            this.jComboBox1.addItem(new ResultType("Number 1", "Normal"));
            this.jComboBox1.addItem(new ResultType("Number 2", "Normal"));
            this.jComboBox1.addItem(new ResultType("Number 3", "A VERY VERY VERY VERY long text"));
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jComboBox1 = new javax.swing.JComboBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBox1ActionPerformed(evt);
            getContentPane().add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 110, -1));
            pack();
        }// </editor-fold>
        private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    final NewJFrame frame = new NewJFrame();
                    frame.setVisible(true);
        private PopupMenuListener getPopupMenuListener() {
            return new PopupMenuListener() {
                @Override
                public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                    // We will have a much wider drop down list.
                    adjustPopupWidth(jComboBox1);
                @Override
                public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                @Override
                public void popupMenuCanceled(PopupMenuEvent e) {
         * Adjust popup for combo box, so that horizontal scrollbar will not display.
         * Resize JComboBox dropdown doesn't work without customized ListCellRenderer
         * http://www.camick.com/java/source/BoundsPopupMenuListener.java
         * @param comboBox The combo box
        public static void adjustPopupWidth(JComboBox comboBox) {
            if (comboBox.getItemCount() == 0) return;
            Object comp = comboBox.getAccessibleContext().getAccessibleChild(0);
            if (!(comp instanceof BasicComboPopup)) {
                return;
            BasicComboPopup popup = (BasicComboPopup)comp;
            JList list = popup.getList();
            JScrollPane scrollPane = getScrollPane(popup);
            // Just to be paranoid enough.
            if (list == null || scrollPane == null) {
                return;
            //  Determine the maximimum width to use:
            //  a) determine the popup preferred width
            //  b) ensure width is not less than the scroll pane width
            int popupWidth = list.getPreferredSize().width
                            + 5  // make sure horizontal scrollbar doesn't appear
                            + getScrollBarWidth(popup, scrollPane);
            Dimension scrollPaneSize = scrollPane.getPreferredSize();
            popupWidth = Math.max(popupWidth, scrollPaneSize.width);
            //  Adjust the width
            scrollPaneSize.width = popupWidth;
            scrollPane.setPreferredSize(scrollPaneSize);
            scrollPane.setMaximumSize(scrollPaneSize);
         *  I can't find any property on the scrollBar to determine if it will be
         *  displayed or not so use brute force to determine this.
        private static int getScrollBarWidth(BasicComboPopup popup, JScrollPane scrollPane) {
            int scrollBarWidth = 0;
            JComboBox comboBox = (JComboBox)popup.getInvoker();
            if (comboBox.getItemCount() > comboBox.getMaximumRowCount()) {
                JScrollBar vertical = scrollPane.getVerticalScrollBar();
                scrollBarWidth = vertical.getPreferredSize().width;
            return scrollBarWidth;
         *  Get the scroll pane used by the popup so its bounds can be adjusted
        private static JScrollPane getScrollPane(BasicComboPopup popup) {
            JList list = popup.getList();
            Container c = SwingUtilities.getAncestorOfClass(JScrollPane.class, list);
            return (JScrollPane)c;
        // Variables declaration - do not modify
        private javax.swing.JComboBox jComboBox1;
        // End of variables declaration
    }Edited by: yccheok on Jan 13, 2011 9:35 AM

    Are these two lines intentionally or is it just a mismatch?
    jLabel2.setMaximumSize(new java.awt.Dimension(100, 14));
    jLabel2.setMinimumSize(new java.awt.Dimension(200, 14));
    2) But 1st row and 2nd row cell renderer, do not know 3rd row is holding such a long string.There is only one cell renderer for all rows, so no need for the rows to know each other.
    To calculate the exact maximum width of column two, you have to check each entry.
    If you can do this BEFORE creating the combo, you could do this in a loop similar to this pseudo code
    FontMetrics fm= jComboBox1.getFontMetrics(jComboBox1.getFont());
    foreach (column2String) {
      int length= fm.stringWidth(column2String);
      if (length>max) max= length;
    }Now you have a max value to dimension jLabel2 in your renderer.
    If you don't fill your combo in one go, but rather at runtime, you have to check at each
    jComboBox1.addItem(...)
    whether the string for label2 is extending the current max, redefine max, and repaint the combo.
    This second approach I haven't done so far, but that's how I would try.

  • Foreign key constraint on multi-column primary key accepts 1 empty column!?

    Hi, we have a reference table with a two-column primary key. In the child table there is a non-mandatory foreign key constraint to this table. So if both child columns are null it's ok too. But now we see that if one of the two child table columns that build up the foreign key is null, the other column can have any (non-existant in the master-tabel) value you like!? That does not make sense.
    Can anyone explain this to me???
    Regards, Paul.

    Paul, I believe that this is in accordance to the ANSI SQL standard requirement for the treatment of nulls in a multi-column FK. In any case Oracle specifically states this is the way FK work From the 10 Concepts manual, Ch 21 Data Integrity, topic Nulls and Foreign Keys:
    The relational model permits the value of foreign keys either to match the referenced primary or unique key value, or be null. If any column of a composite foreign key is null, then the non-null portions of the key do not have to match any corresponding portion of a parent key. <<HTH -- Mark D Powell --

  • Text query using a Multi Column datastore index slow

    I have created a text index using multi column datastore preference. I have specified two clob columns in my preference. Searching on this new index works, but it is slower than I expected.
    I have done the following comparison:
    My original two clob columns are: DocumentBody and DocumentFields. I have built an individual text index on each column. My new column with Multi Column index is DocumentBodyAndFields;
    I did two queries:
    1. search 'dog' on DocumentBody UNION search 'dog' on DocumentFields;
    2. search 'dog' on DocumentBodyAndFields;
    I would think the second search should be faster than the first one because it is a single query. But this is not the case. The second query is consistently slower than the first query by about 10-20%.
    Things are getting much worse when I search on preceding wildcards. If I search '%job', the multi column index is twice as slow as the first query! I am very confused by this result. Is this a bug?

    I am unable to reproduce the performance problem. In my tests, the search that uses the multicolumn_datastore performs better, as demonstrated below. Can you provide a similar test case that shows the table structure, datastore, index creations, and explain plan?
    SCOTT@orcl_11g> CREATE TABLE your_tab
      2    (DocumentId            NUMBER,
      3       DocumentBody            CLOB,
      4       DocumentFields            CLOB,
      5       DocumentBodyAndFields  VARCHAR2 (1))
      6  /
    Table created.
    SCOTT@orcl_11g> INSERT ALL
      2  INTO your_tab VALUES (-1, 'adog', 'bdog', NULL)
      3  INTO your_tab VALUES (-2, 'adog', 'whatever', NULL)
      4  INTO your_tab VALUES (-3, 'whatever', 'bdog', NULL)
      5  SELECT * FROM DUAL
      6  /
    3 rows created.
    SCOTT@orcl_11g> INSERT INTO your_tab
      2  SELECT object_id, object_name, object_name, NULL
      3  FROM   all_objects
      4  /
    69063 rows created.
    SCOTT@orcl_11g> BEGIN
      2    CTX_DDL.CREATE_PREFERENCE
      3        ('your_datastore', 'MULTI_COLUMN_DATASTORE');
      4    CTX_DDL.SET_ATTRIBUTE
      5        ('your_datastore', 'COLUMNS', 'DocumentBody, DocumentFields');
      6  END;
      7  /
    PL/SQL procedure successfully completed.
    SCOTT@orcl_11g> CREATE INDEX your_idx1 ON your_tab (DocumentBody)
      2  INDEXTYPE IS CTXSYS.CONTEXT
      3  /
    Index created.
    SCOTT@orcl_11g> CREATE INDEX your_idx2 ON your_tab (DocumentFields)
      2  INDEXTYPE IS CTXSYS.CONTEXT
      3  /
    Index created.
    SCOTT@orcl_11g> CREATE INDEX your_idx3 ON your_tab (DocumentBodyAndFields)
      2  INDEXTYPE IS CTXSYS.CONTEXT
      3  PARAMETERS ('DATASTORE your_datastore')
      4  /
    Index created.
    SCOTT@orcl_11g> EXEC DBMS_STATS.GATHER_TABLE_STATS (USER, 'YOUR_TAB')
    PL/SQL procedure successfully completed.
    SCOTT@orcl_11g> SET TIMING ON
    SCOTT@orcl_11g> SET AUTOTRACE ON EXPLAIN
    SCOTT@orcl_11g> SELECT DocumentId FROM your_tab
      2  WHERE  CONTAINS (DocumentBody, '%dog') > 0
      3  UNION
      4  SELECT DocumentId FROM your_tab
      5  WHERE  CONTAINS (DocumentFields, '%dog') > 0
      6  /
    DOCUMENTID
            -3
            -2
            -1
    Elapsed: 00:00:00.65
    Execution Plan
    Plan hash value: 4118340734
    | Id  | Operation                     | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT              |           |     4 |   576 |     2 (100)| 00:00:01 |
    |   1 |  SORT UNIQUE                  |           |     4 |   576 |     2 (100)| 00:00:01 |
    |   2 |   UNION-ALL                   |           |       |       |            |          |
    |   3 |    TABLE ACCESS BY INDEX ROWID| YOUR_TAB  |     2 |   288 |     0   (0)| 00:00:01 |
    |*  4 |     DOMAIN INDEX              | YOUR_IDX1 |       |       |     0   (0)| 00:00:01 |
    |   5 |    TABLE ACCESS BY INDEX ROWID| YOUR_TAB  |     2 |   288 |     0   (0)| 00:00:01 |
    |*  6 |     DOMAIN INDEX              | YOUR_IDX2 |       |       |     0   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       4 - access("CTXSYS"."CONTAINS"("DOCUMENTBODY",'%dog')>0)
       6 - access("CTXSYS"."CONTAINS"("DOCUMENTFIELDS",'%dog')>0)
    SCOTT@orcl_11g> SELECT DocumentId FROM your_tab
      2  WHERE  CONTAINS (DocumentBodyAndFields, '%dog') > 0
      3  /
    DOCUMENTID
            -1
            -2
            -3
    Elapsed: 00:00:00.28
    Execution Plan
    Plan hash value: 65113709
    | Id  | Operation                   | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT            |           |     4 |    76 |     0   (0)| 00:00:01 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| YOUR_TAB  |     4 |    76 |     0   (0)| 00:00:01 |
    |*  2 |   DOMAIN INDEX              | YOUR_IDX3 |       |       |     0   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - access("CTXSYS"."CONTAINS"("DOCUMENTBODYANDFIELDS",'%dog')>0)
    SCOTT@orcl_11g>

  • "The CREATE USER statement must be the only statement in the batch" in SQL Azure - why? what to do?

    I'm getting an error on a line in the middle of a larger sql script, only in SQL Azure.
    IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'foouser')
    CREATE USER [foouser] FOR LOGIN [foouser] WITH DEFAULT_SCHEMA=[dbo]
    GO
    Error: "The CREATE USER statement must be the only statement in the batch."
    I don't actually understand what 'the only statement in the batch' means.
    What is a batch? Is it a SQL file? Is it related to a 'GO' statement or an 'IF' statement? What is the reason for the error? And how do I avoid it?
    Thanks,
    Tim

    >IF...ELSE imposes conditions on the execution of a Transact-SQL statement
    I understand the general purpose of an If statement. I could let go of our definition of statement counting disagreeing too except that because of the error I'm stuck.
    It's less important for Create User but what I am really puzzled over now is a very similar issue how am I supposed to do a safe version of CREATE LOGIN, when I don't know whether a login has been previously created on the server or whether I
    am setting up the database on a clean server?
    IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE name = N'foouser')
    CREATE LOGIN [foouser] WITH PASSWORD = 'asdfasdf'
    GO
    If I try and execute this script, it throws the same error as above.
    The first unworkable workaround idea is to omit the if statement
    CREATE LOGIN [foouser] WITH PASSWORD = 'asdfasdf'
    GO
    But if the login already exists on the server (because a similar script was already run), then the script throws an error.
    The second unworkable workaround idea is to do
    DROP LOGIN [foouser]
    GO
    CREATE LOGIN [foouser] WITH PASSWORD = 'asdfasdf'
    GO
    Obviously this throws an error in the second block if the login doesn't already exist on the server.
    The third workaround idea I have is to go conditional by putting an IF condition around DROP instead of CREATE:
    Unfortunately that doesn't work for me either!
    "The DROP LOGIN statement must be the only statement in the batch"
    (This is despite the fact that 'drop login' is listed on the
    supported commands page, not the partially supported page..?! Which disagrees with the notes on
    this page.)
    Anyway the real question I am interesting in addressing is: is there actually a way to have a 'Create/Delete login
    if exists' operation which is SQL-Azure compatible and doesn't throw me error messages (which messes with the sql execution tool I am using)?
    If there is no way, I would like to believe it's because it would be a bad idea to do this. But in that case why is it a bad idea?
    Tim

  • Does Indes stats get auto collected when stats auto collection is on?

    In 10g and 11g, does Index stats get auto collected when stats auto collection is on (by default)? When do we need it? As I saw nothing in INDEX_STATS in both 10g and 11g.
    Thanks.

    Default is FOR ALL COLUMNS SIZE AUTO. statistics for indexes were also collected.
    Index stats will be populated only if you validate structure. The view INDEX_STATS is only populated after you run an analyze index name validate structure. if you log out you no longer see the statistics
    analyze index <index_name> validate structure;
    select * from index_stats;
    You'll see the information.
    Edited by: Anantha on Jan 12, 2009 2:16 PM
    Edited by: Anantha on Jan 12, 2009 2:25 PM

  • Problem in implementing "Multi-Master Replication"

    Hi,
    I am trying to implement "Multi-Master Replication", where both sites will try to act as Master, when Site1 is down the other site will take control and data will be updated at Site2 and vice-versa.
    I have created REPADMIN user at both the site.
    create user repadmin identified by repadmin;
    grant connect, resource to repadmin;
    execute dbms_repcat_admin.grant_admin_any_schema(&lsquo;repadmin');
    grant comment any table to repadmin;
    grant lock any table to repadmin;
    execute dbms_defer_sys.register_propagator(&lsquo;repadmin');
    Then I have created DBLink at both sites:
    connect repadmin/[email protected]
    create database link MYDB.WORLD
    connect to repadmin identified by repadmin
    using 'MYDB.WORLD';
    connect repadmin/[email protected]
    create private database link NAVDB.WORLD
    connect to repadmin identified by repadmin using 'NAVDB.WORLD';
    Then created schedules for Push and Perge jobs.
    -- Add jobs to NAVDB
    connect repadmin/repadmin@navdb
    begin
    dbms_defer_sys.schedule_push(
    destination =&gt; 'MYDB.WORLD',
    interval =&gt; 'SYSDATE + 1/(60*24)',
    next_date =&gt; sysdate,
    stop_on_error =&gt; FALSE,
    delay_seconds =&gt; 0,
    parallelism =&gt; 1);
    end;
    begin
    dbms_defer_sys.schedule_purge(
    next_date =&gt; sysdate,
    interval =&gt; 'sysdate + 1/24',
    delay_seconds =&gt; 0,
    rollback_segment =&gt; '');
    end;
    -- Add jobs to MYDB
    connect repadmin/repadmin@mydb
    begin
    dbms_defer_sys.schedule_push(
    destination =&gt; 'NAVDB.WORLD',
    interval =&gt; 'SYSDATE + 1/(60*24)',
    next_date =&gt; sysdate,
    stop_on_error =&gt; FALSE,
    delay_seconds =&gt; 0,
    parallelism =&gt; 1);
    end;
    begin
    dbms_defer_sys.schedule_purge(
    next_date =&gt; sysdate,
    interval =&gt; 'sysdate + 1/24',
    delay_seconds =&gt; 0,
    rollback_segment =&gt; '');
    end;
    Then created "Master Group Site" at Site1:
    connect repadmin/repadmin@navdb
    BEGIN
    DBMS_REPCAT.CREATE_MASTER_REPGROUP(
    gname =&gt; '"GROUP1"',
    qualifier =&gt; '',
    group_comment =&gt; '');
    END;
    Add desired table object for Replication:
    BEGIN
    DBMS_REPCAT.CREATE_MASTER_REPOBJECT(
    gname =&gt; '"GROUP1"',
    type =&gt; 'TABLE',
    oname =&gt; '"AUTHOR"',
    sname =&gt; '"PUBS"');
    END;
    Set Primary Key column:
    BEGIN
    DBMS_REPCAT.SET_COLUMNS(
    sname =&gt; '"PUBS"',
    oname =&gt; '"AUTHOR"',
    column_list =&gt; '"AUTHOR_KEY"');
    END;
    Resume Master Activity at Site1:
    BEGIN
    DBMS_REPCAT.RESUME_MASTER_ACTIVITY(
    gname =&gt; '"GROUP1"');
    END;
    Add another Master Site as Site2:
    connect repadmin/repadmin@navdb
    BEGIN
    DBMS_REPCAT.SUSPEND_MASTER_ACTIVITY(
    gname =&gt; '"GROUP1"');
    END;
    BEGIN
    DBMS_REPCAT.ADD_MASTER_DATABASE(
    gname =&gt; '"GROUP1"', master =&gt; &lsquo;MYDB.WORLD');
    END;
    BEGIN
    DBMS_REPCAT.RESUME_MASTER_ACTIVITY(
    gname =&gt; '"GROUP1"');
    END;
    I have executed above steps as shown in attached PDF file. Now I am trying to update one row in "Author" table and it is giving error like:
    ORA-23326: object group "PUBLIC"."GROUP1" is quiesced
    As per the description given for error in some help file, I am trying to suspend the activity, then it is give me same error like:
    SQL&gt; BEGIN
    2 DBMS_REPCAT.SUSPEND_MASTER_ACTIVITY(
    3 gname =&gt; '"GROUP1"');
    4 END;
    5 /
    BEGIN
    ERROR at line 1:
    ORA-23326: object group "PUBLIC"."GROUP1" is quiesced
    ORA-06512: at "SYS.DBMS_SYS_ERROR", line 95
    ORA-06512: at "SYS.DBMS_REPCAT_MAS", line 4195
    ORA-06512: at "SYS.DBMS_REPCAT", line 946
    ORA-06512: at line 2
    Here I am stuck up and cannot perform any DML operation on the Replicated object.
    Look into the matter and suggest something if anyone can.
    Thanks,
    Tapan Trivedi

    You're probably going to have to rethink this.
    Even if your replication agreements are not encrypted, it is likely that your userPassword attributes are hashed. If they're not, you could just ask either master for the cleartext userPassword anyways, and no need to try to sniff it out of replication traffic.

  • How to prevent multi-column list box showing an extra column

    I am using a multi-column list box to display data and to allow the user to enter new values. More columns are used than are actually displayed within the bounds of the listbox control. Using an event structure the user is able to scroll left and right along the columns of the list box to select the appropriate field. I am using the 'Edit Position' property to highlight the particular field that the user is selecting. This technique works well and the listbox scrolls left and right to display the selected fields correctly.
    If the listbox has, say, 10 columns with only 5 being visible within the displayed width, then I clamp the Edit Position to a maximum column value of 9 to prevent the list box from continuing to scroll right into unused columns. This works fine, except that when the user scrolls to the 10th column, the listbox control always shows a blank 11th column. The 11th column cannot be selected. It would appear that this is default behaviour for the listbox control in that an additional column is always displayed relative to the Edit Position. In my particular application it is untidy to have this blank column appearing. I have tried a workaround by programmatically writing to the 'TopLeft' property of the listbox. This partially works by ensuring that the blank 11th column is never displayed, however, despite the Edit Position being correct to select the 10th column, the field in the 10th column is no longer highlighted and the user cannot enter a new value.
    Does anyone know of a method for preventing the blank additional column from appearing?

    Ok - I have attached an example which demonstrates the issue. This is produced with LV 2012. Open the project and then the 'Multi column listbox.vi'. Run the vi and use the right/left arrows to move between cells in the listbox. Observe that unused (unwanted) columns are always displayed to the right.
    Thanks for any help..
    Attachments:
    Test Multi column listbox.zip ‏62 KB

  • Needs multi column dynamic combo box using C#

    I need a dynamic Combo box to display multi columns on Drop Down Event 
    such as Stock Code, Make, Model,Sub Model, Measurement Type and so on for  my C# Application with Columns Headers 
    Please Help Me
    Thanks in Advance

    You should create a class that represents your model and then you could use a CompositeCollection as the ItemsSource of the ComboBox.
    Here is an example for you:
    namespace WpfApplication59
    public class YourModel
    public string StockCode { get; set; }
    public string Model { get; set; }
    //+ the rest of your properties
    MainWindow.xaml.cs:
    public partial class MainWindow : Window
    public MainWindow()
    InitializeComponent();
    List<YourModel> models = new List<YourModel>();
    models.Add(new YourModel() { Model = "m1", StockCode ="c1"});
    models.Add(new YourModel() { Model = "m2", StockCode = "c2" });
    cb.ItemsSource = models;
    MainWindow.xaml:
    <ComboBox x:Name="cb" Grid.IsSharedSizeScope="True" ItemsSource="{DynamicResource items}"
    xmlns:local="clr-namespace:WpfApplication59">
    <ComboBox.Resources>
    <CompositeCollection x:Key="items">
    <ComboBoxItem IsEnabled="False">
    <Grid TextElement.FontWeight="Bold">
    <Grid.ColumnDefinitions>
    <ColumnDefinition SharedSizeGroup="A"/>
    <ColumnDefinition Width="5"/>
    <ColumnDefinition SharedSizeGroup="B"/>
    </Grid.ColumnDefinitions>
    <Grid.Children>
    <TextBlock Grid.Column="0" Text="Model"/>
    <TextBlock Grid.Column="2" Text="Stock Code"/>
    </Grid.Children>
    </Grid>
    </ComboBoxItem>
    <Separator/>
    <CollectionContainer Collection="{Binding Source={x:Reference cb}, Path=DataContext}"/>
    </CompositeCollection>
    <DataTemplate DataType="{x:Type local:YourModel}">
    <Grid>
    <Grid.ColumnDefinitions>
    <ColumnDefinition SharedSizeGroup="A"/>
    <ColumnDefinition Width="5"/>
    <ColumnDefinition SharedSizeGroup="B"/>
    </Grid.ColumnDefinitions>
    <Grid.Children>
    <TextBlock Grid.Column="0" Text="{Binding Model}"/>
    <TextBlock Grid.Column="2" Text="{Binding StockCode}"/>
    </Grid.Children>
    </Grid>
    </DataTemplate>
    </ComboBox.Resources>
    </ComboBox>
    You could restyle the the templates (Grids) as per your requirements.
    Please remember to mark helpful posts as answer to close your threads and then start a new thread if you have a new question.

  • Context v catsearch and multi-column scoring

    hi everybody-
    i'm a newbie to text search. need to eval oracle text and lucene for our application.
    the docs aren't answering my questions, and i have done some searching here, but no luck.
    here is our app.
    DATA
    we have a database of genes (for the malaria parasite). it is like a catalog of genes. however, like many other catalogs these days, we have commentary, which we store in clobs. so, most fields are short but a couple are clobs.
    QUERYING
    it seems to me that we would be very well served by the google model: the user types one or more words, and the results are ranked.
    (a) i don't see the need for boolean or NEAR. like google, a simple rule should hold: the more words that are matched, the better. the closer together the better. i would like a score that indicates how good the match is, based on these criteria.
    - does oracle text have an implementation of this?
    - if not, how can i do it?
    (b) we will be searching many columns, presumably each with its own CONTAINS query. they need to be ranked. i think that if the score returned by contains can reflect the rules in (a) then i can do all the ranking i need by just multiplying each contains by a ranking. (this seems simpler for our needs than the very confusing solutions described in this thread: Re: Multi column with CONTEXT index and ranking
    (c) because i want to search multiple columns, and because some of them are clobs, am i correct in thinking this will force me to go uniformly with CONTAINS instead of somehow mixing CATSEARCH (for the small columns) and CONTAINS (for the clobs) in one sql query?
    thanks much,
    steve

    (1) in the template query you show above, can i do
    the trick where i multiply each different WITHIN by
    a weight for that field?Yes, I demonstrated that by multiplying the within clause for commentary1 by 2.
    (2) i am looking at SNIPPET now as well. would i
    be able to pass the complex query template into the
    text_query param of CTX_DOC.SNIPPET?No,  The progressive query relaxation uses a query template and according to the documenteation:
    "CTX_DOC.SNIPPET does not support the use of query templates."
    However, you can use the query with the progressive query relaxation template to find
    the rows you want and rank them by score, then use ctx_doc.snippet to mark the
    words and get the surrounding words, as demonstrated below.  It may be a little hard to
    view, as the marking of the words conflicts with some of the formatting on this forum. 
    SCOTT@orcl_11g>
    SCOTT@orcl_11g> CREATE TABLE malaria_catalog
      2    (gene          VARCHAR2 (5),
      3       commentary1  CLOB,
      4       commentary2  CLOB)
      5  /
    Table created.
    SCOTT@orcl_11g> INSERT ALL
      2  INTO malaria_catalog VALUES ('gene1',
      3  'This is a little bit longer entry with word1 followed by word2 and word3 to demonstrate the snippet function.',
      4  'This is a second line with word1 word2 word3 in commentary2.')
      5  SELECT * FROM DUAL
      6  /
    1 row created.
    SCOTT@orcl_11g> BEGIN
      2    CTX_DDL.CREATE_PREFERENCE ('your_datastore', 'MULTI_COLUMN_DATASTORE');
      3    CTX_DDL.SET_ATTRIBUTE ('your_datastore', 'COLUMNS', 'gene, commentary1, commentary2');
      4    CTX_DDL.CREATE_SECTION_GROUP ('your_sec_group', 'BASIC_SECTION_GROUP');
      5    CTX_DDL.ADD_FIELD_SECTION ('your_sec_group', 'commentary1', 'commentary1', TRUE);
      6    CTX_DDL.ADD_FIELD_SECTION ('your_sec_group', 'commentary2', 'commentary2', TRUE);
      7  END;
      8  /
    PL/SQL procedure successfully completed.
    SCOTT@orcl_11g> CREATE INDEX your_index ON malaria_catalog (gene)
      2  INDEXTYPE IS CTXSYS.CONTEXT
      3  PARAMETERS
      4    ('DATASTORE     your_datastore
      5        SECTION GROUP     your_sec_group')
      6  /
    Index created.
    SCOTT@orcl_11g> VARIABLE search_string VARCHAR2 (100)
    SCOTT@orcl_11g> EXEC :search_string := 'word1 word2 word3'
    PL/SQL procedure successfully completed.
    SCOTT@orcl_11g> EXEC CTX_DOC.SET_KEY_TYPE ('ROWID')
    PL/SQL procedure successfully completed.
    SCOTT@orcl_11g> COLUMN snippet FORMAT A60
    SCOTT@orcl_11g> SELECT SCORE (1),
      2           CTX_DOC.SNIPPET
      3             ('YOUR_INDEX',
      4              ROWID,
      5              REPLACE (:search_string, ' ', ' OR ')) AS snippet
      6  FROM   malaria_catalog mc
      7  WHERE  CONTAINS
      8             (gene,
      9              '<query>
    10              <textquery lang="ENGLISH" grammar="CONTEXT">
    11                <progression>
    12                  <seq>'
    13                  || '(' || REPLACE (:search_string, ' ', ' NEAR ') || ' WITHIN commentary1) * 2 OR '
    14                  || REPLACE (:search_string, ' ', ' NEAR ') || ' WITHIN commentary2' ||
    15                  '</seq>
    16                  <seq>'
    17                  || '(' || REPLACE (:search_string, ' ', ' ACCUM ') || ' WITHIN commentary1) * 2 OR '
    18                  || REPLACE (:search_string, ' ', ' ACCUM ') || ' WITHIN commentary2' ||
    19                 '</seq>
    20                </progression>
    21              </textquery>
    22              <score datatype="INTEGER" algorithm="COUNT"/>
    23            </query>',
    24              1) > 0
    25  ORDER  BY SCORE (1) DESC
    26  /
      SCORE(1) SNIPPET
            67 is a little bit longer entry with <b>word1</b> followed by <
               b>word2</b> and <b>word3</b> to demonstrate the snippet func
               tion<b>...</b>line with <b>word1</b> <b>word2</b> <b>word3</
               b> in commentary2
    SCOTT@orcl_11g>

  • Multi-column BITMAP index vs. multiple BITMAP indices?

    Given the table (simple, made-up example):
    CREATE TABLE applicant_diversity_info (
    applicant_diversity_id NUMBER(12), PRIMARY KEY(applicant_diversity_id),
    apply_date DATE,
    ssn_salted_md5 RAW(16),
    gender CHAR(1), CHECK ( (gender IS NULL OR gender IN ('M','F')) ),
    racial_continent VARCHAR2(30), CHECK ( (racial_continent IS NULL
    OR racial_continent IN ('Europe','Africa','America','Asia_Pacific')) ),
    ethnic_supergroup VARCHAR2(30), CHECK ( (ethnic_supergroup IS NULL OR ethnic_supergroup IN ('Latin American','Other')) ),
    hire_salary NUMBER(11,2),
    hire_month DATE,
    termination_salary NUMBER(11,2),
    termination_month DATE,
    termination_cause VARCHAR2(30), CHECK ( (termination_cause IS NULL
    OR termination_cause IN ('Resigned','Leave of Absence','Laid Off','Performance','Cause')) )
    Oracle (syntactically) allows me to create either one BITMAP index over all four small-cardinality columns
    CREATE BITMAP INDEX applicant_diversity_diversity_idx ON applicant_diversity_info (
    gender, racial_continent, ethnic_supergroup, termination_reason );
    or four independent indexes
    CREATE BITMAP INDEX applicant_diversity_gender_idx ON applicant_diversity_info ( gender );
    CREATE BITMAP INDEX applicant_diversity_race_idx ON applicant_diversity_info ( raceial_continent );
    etc.
    What is the difference between the two approaches; is there any meaningful difference in disk-space between the one multi-colum index and the four single-column indexes? Does it make a difference in what the query-planner will consider?
    And, if I define one multi-column BITMAP index, does the order of columns matter?

    >
    What is the difference between the two approaches; is there any meaningful difference in disk-space between the one multi-colum index and the four single-column indexes? Does it make a difference in what the query-planner will consider?
    And, if I define one multi-column BITMAP index, does the order of columns matter?
    >
    You may want to read this two-part blog, that answers that exact question, by recognized expert Richard Foote
    http://richardfoote.wordpress.com/2010/05/06/concatenated-bitmap-indexes-part-i-two-of-us/
    http://richardfoote.wordpress.com/2010/05/12/concatenated-bitmap-indexes-part-ii-everybodys-got-to-learn-sometime/
    As with many things Oracle the answer is 'it depends'.
    In short the same considerations apply for a concatenated index whether it is bitmap or b-tree: 1) will the leading column usually be in the predicate and 2) will most or all of the index columns be specified in the queries.
    Here are some quotes from part 1
    >
    Many of the same issues and factors in deciding to create a single, multi-column index vs. several, single column indexes apply to Bitmap indexes as they do with B-Tree indexes, although there are a number of key differences to consider as well.
    Another thing to note regarding a concatenated Bitmap index is that the potential number of index entries is a product of distinct combinations of data of the indexed columns.
    A concatenated Bitmap index can potentially use less or more space than corresponding single column indexes, it depends on the number of index entries that are derived and the distribution of the data with the table.
    >
    Here is the lead quote from part 2
    >
    The issues regarding whether to go for single column indexes vs. concatenated indexes are similar for Bitmap indexes as they are for B-Tree indexes.
    It’s generally more efficient to access a concatenated index as it’s only the one index with less processing and less throwaway rowids/rows to contend with. However it’s more flexible to have single column indexes, especially for Bitmap indexes that are kinda designed to be used concurrently, as concatenated indexes are heavily dependant on the leading column being known in queries.

Maybe you are looking for

  • Is Adobe Flex suitable to build a Multimedia Presentation?

    I am looking for some advice on the suitability of using Adobe Flex for building a Multimedia presentation system. I have watched numerous videos about Flex and even tried some tutorials but before I make a decision on Technologies for a project I am

  • APO Demand Planning - Navigational Attributes BADI

    Hi, I have an issue in that I need a Navigational Attribute to be able to store the GUID for a Forecast Profile to a Selection. In standard, only a selection with Key Characteristics can do this. It is not practical for us to use a Key Characteristic

  • Foreign Dialogue Subtitles in English Audio Track not working

    I just bought Ocean's 13 HD in iTunes/iCloud.  How can I get iTunes to display the foreign dialouge substitles that are in the English audio track? I also have the Bluray, and these subtitles display fine when at time the movie is set in Mexico. I do

  • How can i upload music with the new itunes

    so i updated the new itunes and now when im syncing my ipod the music isnt going in. can i burn the music then put it in my computer and itunes will accept it and put it into my ipod? can i un-update my itunes 11? please help

  • Passing variables on the URL

    Is it possibe to pass variables into edge from the URL? I can see a scenario where you could send people a link like site.com/myedgeanimation/?=bob or site.com/myedgeanimation/?=alice and BOB and ALICE could each get a personalized animation.