ORDER BY timestamp column as a string

Does any one have any tips/tricks for using an ORDER BY clause for a timestamp column that is a string?
I am developing a UNION query that combines data from a table and an audit history table to show current data plus historical data.
I had to convert the timestamp column to a string so the datatypes would match for the UNION query, but now they ORDER BY clause does not work.
For example:
SELECT
location,
'CURRENT' as VALID_DATE
FROM
person
UNION
SELECT
location,
TO_CHAR(audit_date)
FROM
person_audit
ORDER BY 2 DESC

Hi,
user2269823 wrote:
Using the 'yyyy-mm-dd' format works pretty well when ordering by the string. It looks like when ordering by a string Oracle just looks at the characters sequentially.
For example:
2009-1-14
2008-12-31
2007-6-6Looks like you have changed the format slightly?
Consider this
SQL> select TO_CHAR(sysdate,'FMyyyy-mm-dd')
      , TO_CHAR(sysdate, 'yyyy-mm-dd') from dual;
TO_CHAR(SY TO_CHAR(SY
2009-5-28  2009-05-28
SQL>Looks fine with me, as long as you don't have the FM format model modifer.
Regards
Peter

Similar Messages

  • Problem fetching multiple values in a TIMESTAMP column

    Hi all,
    I'm having a problem trying to fetch multiple values in a TIMESTAMP column. I can successfully fetch the TIMESTAMP column if I do the following:
    OCIDateTime tstmpltz = (OCIDateTime )NULL;
    rc = OCIDescriptorAlloc(p_env,(dvoid **)&tstmpltz, OCI_DTYPE_TIMESTAMP,
    0, (dvoid **)0);
    rc = OCIDefineByPos(p_sql, &p_dfn, p_err, 1, &tstmpltz, sizeof(tstmpltz),
    SQLT_TIMESTAMP, 0, 0, 0, OCI_DEFAULT);
    This works fine. I can then do what I want with the OCIDateTime variable tstmpltz, like convert it to a text string, etc.
    But what I am trying to do is fetch many rows of data that could include a TIMESTAMP column. For character columns this is no problem. I simply allocate a buffer of the correct width and length and then do my OCIDefineByPos to point to the start and the character data gets filled in. Same for numeric columns as well.
    I can do this with a TIMESTAMP column if I do the OCIDefineByPos with a column type of SQLT_CHR. But the problem I'm running into when I do things this way is if I fetch a Timestamp value that is before 1950 I believe it is, I get back the wrong century. So for instance 1900 comes back as 2000. I think this is because the default date format when fetching is a 2 digit year. So I've tried to the do following:
    long fetchrows = 50;
    unsigned char *descpp1;
    descpp1 = (unsigned char *)calloc(fetchrows, sizeof (OCIDateTime *));
    int i;
    for (i = 0; i != fetchrows; i++)
    /* Allocate descriptors */
    rc = OCIDescriptorAlloc((void *)p_env,(void **)&descpp1[i * sizeof (OCIDateTime *)], OCI_DTYPE_TIMESTAMP,
    0,(void **)0);
    // Bind the column
    rc = OCIDefineByPos(p_sql, &p_dfn, p_err, 1, descpp1, sizeof(descpp1),
    SQLT_TIMESTAMP, 0, 0, 0, OCI_DEFAULT);
    rc = OCIStmtExecute(p_svc, p_sql, p_err, (ub4) 50, (ub4) 0,
    (CONST OCISnapshot *) NULL, (OCISnapshot *) NULL,
    OCI_DEFAULT);
    And I get an "ORA-01403: no data found" error. I'm missing something here but I can't figure out what it is. Is this proper way to fetch multiple Timestamp columns ?
    Thanks,
    Nick

    Hi Nick,
    I think the "trick" here is that when you call OCIDescriptorAlloc normally you would pass a pointer to an OCIDateTime pointer (i.e. OCIDateTime**). However, you're being sneaky here and using unsigned char * with malloc/calloc for the reasons you have already mentioned. So, that changes things a bit because in this scenario the "destination address" where OCI is going to put the address for the OCIDateTime descriptor is in the memory you have dynamically allocated rather than in the target pointer of an OCIDateTime** declaration. So far so good, but the problem, as you've discovered, comes about when you need to get the OCIDateTime* to pass into the OCIDateTimeToText function. In your call you have this:
    (OCIDateTime *)descpp1[0 * sizeof (OCIDateTime *)]However, that isn't the address of the descriptor it's a pointer to the address so, depending on your actual calls, etc. you'll either get a memory violation or an invalid OCI handle error. What you can do is get the address from that memory location and stuff it into a proper OCIDateTime* and then it can be used in the OCIDateTimeToText function.
    I'm probably doing a terrible job explaining it, but I have cobbled together a sample which does what you want (at least as far as I can tell). Of course, being OCI, there's a fair bit of code, but here's the main parts.
    I created a table called "ts_test" that has the following structure and sample data:
    SQL> desc ts_test
    Name             Null?    Type
    TS_ID                     NUMBER
    TS_VALUE                  TIMESTAMP(3)
    SQL> select * from ts_test order by ts_id;
         TS_ID TS_VALUE
             1 01-JAN-09 08.00.00.123 AM
             2 01-JAN-09 12.34.56.789 PM
             3 01-JAN-09 04.46.00.046 PM
             4 01-JAN-09 10.00.00.314 PM
    4 rows selected.I use the same query as above in the OCI sample code to get the values back out of the table.
      ** will hold pointers to TimeStamp Descriptor memory
      unsigned char *pTSD = (unsigned char *) NULL;
      ** temp pointer used with descriptors
      OCIDateTime *pTemp = NULL;
      ** allocate memory for the ts_id column
      if ((pID_val = (ub4 *) malloc(sizeof(ub4) * arrsize)) == NULL)
        printf("Failed to allocate memory for pID_val!\n");
        return;
      ** allocate memory for the ts descriptors
      if ((pTSD = (unsigned char *) malloc(sizeof(unsigned char *) * arrsize)) == NULL)
        printf("Failed to allocate memory for pTSD!\n");
        return;
      ** allocate date time descriptors
      for (i = 0; i < arrsize; i++)
        rc = OCIDescriptorAlloc(pDBCtx->envhp,
                                (void **) &pTSD[i * sizeof(OCIDateTime *)],
                                (ub4) OCI_DTYPE_TIMESTAMP,
                                (size_t) 0,
                                (void **) 0);
      ** define the first column in the results
      rc = OCIDefineByPos(stmtp,
                          &defnp,
                          pDBCtx->errhp,
                          (ub4) 1,
                          (void *) pID_val,
                          (sword) sizeof(ub4),
                          (ub2) SQLT_INT,
                          (void *) pID_ind,
                          (ub2 *) 0,
                          (ub2 *) 0,
                          (ub4) OCI_DEFAULT);
      ** define the second column in the results
      rc = OCIDefineByPos(stmtp,
                          &defnp,
                          pDBCtx->errhp,
                          (ub4) 2,
                          (void *) &pTSD[0],
                          (sword) sizeof(OCIDateTime *),
                          (ub2) SQLT_TIMESTAMP,
                          (void *) pTS_ind,
                          (ub2 *) 0,
                          (ub2 *) 0,
                          (ub4) OCI_DEFAULT);
      ** execute the statement
      rc = OCIStmtExecute(pDBCtx->svchp,
                          stmtp,
                          pDBCtx->errhp,
                          (ub4) arrsize,
                          (ub4) 0,
                          (CONST OCISnapshot *) NULL,
                          (OCISnapshot *) NULL,
                          (ub4) OCI_DEFAULT);
      ** get the text value of the timestamp
      ** null-terminate it, and display the value.
      ** the address of the allocated descriptor
      ** is copied from the dynamically allocated
      ** memory to the temp variable and that
      ** is passed to OCIDateTimeToText
      for (i = 0; i < arrsize; i++)
        memcpy((void *) &pTemp, &pTSD[i * sizeof(OCIDateTime *)], sizeof(OCIDateTime *));
        rc = OCIDateTimeToText((void *) pDBCtx->usrhp,
                               pDBCtx->errhp,
                               pTemp,
                               (oratext *) 0,
                               (ub1) 0,
                               (ub1) 3,
                               (oratext *) 0,
                               (size_t) 0,
                               &buflen,
                               buf);
        buf[buflen] = '\0';
        printf("Timestamp value[%d]: %s\n", *pID_val++, buf);
    ...Obviously there's lots left out, but hopefully that can be of some help. I've not really thoroughly reviewed the code so there may be a few things to fix. Anyway, using the above table and data the full sample outputs this on my system:
    Timestamp value[1]: 01-JAN-09 08.00.00.123 AM
    Timestamp value[2]: 01-JAN-09 12.34.56.789 PM
    Timestamp value[3]: 01-JAN-09 04.46.00.046 PM
    Timestamp value[4]: 01-JAN-09 10.00.00.314 PM
    ENTER to continue...Thanks,
    Mark

  • How to get data with out having any date/timestamp columns by year wise

    hi,
    how can i select years wise rows from tables,if that have not any date/timestamp column.

    Well Govind it quite depends on what is the data type of that column and the format in which it is stored.
    If the data type is varchar2/varchar and all the values are in a uniform format then there is no problem. All you need to use is the to_date function to convert the supplied strings to default date format and then use to_char function to only extract the YY or YYYY or RR or RRRR aspect of the data.
    For example: If the column is called 'hire_date' and it's data type is varchar2 and the entries in this column are all in a uniform format, say month,date,year like January,12,1999. What you need to do is convert this string to a default date value using to_date function, like to_date(hire_date,'format_model') In the format model mention the format of the hire_date string. The out put of this function can be fed into to_char to extract the year, like to_char(output_of_to_date,'YYYY')
    I hope you got what I meant. Let me know if it was of any use.

  • Bug: Timestamp columns don't work in automatic row processing

    It appears that automatic row processing doesn't work with timestamp columns. Here is the scenario:
    - I have a view that contains a timestamp column
    - I create an automatic row processing process that reads a row from this view
    - I create a hidden item with a source type of "Database Column" and set its source value to the name of the timestamp column.
    - The value of the hidden input is empty, i.e. value=""
    I found that, as a workaround, if a change the view to convert the timestamp to a string (e.g. SELECT TO_CHAR(LAST_MODIFIED) LAST_MODIFIED rather than SELECT LAST_MODIFIED), it works correctly.
    Adding a format mask or doing the conversion in a "post calculation computation" (e.g. TO_CHAR(:P34_LAST_MODIFIED)) doesn't work.

    Later on in my exploration I found that some of the text boxes on the Keynote inspector were not accepting text, and so I couldn't even change the transition time for a slide. That prompted a restart of the program and that also seems to have solved the problem where the inspector wasn't accepting input for the columns and gutter. It's working now. So watch out for that. No idea what was at the root of it, which is annoying.

  • ODBC errors while retrieving timestamp column

    Hi,
    I created 2 views selecting timestamp column of table ULTBPM_CCHK.CC_APPINFO:
    CREATE OR REPLACE FORCE VIEW "ULTBPM_CCHK"."ERKANDENE_V" ("CCAI_RECORDDATETIME") AS select TO_DATE(TO_CHAR(CCAI_RECORDDATETIME,'DD/MM/YYYY hh24:mi:ss'),'DD/MM/YYY
    Y hh24:mi:ss') CCAI_RECORDDATETIME from ULTBPM_CCHK.CC_APPINFO;
    CREATE OR REPLACE VIEW "ULTBPM_CCHK"."ERKANDENE_V2"
    "CCAI_RECORDDATETIME") AS select CCAI_RECORDDATETIME from ULTBPM_CCHK.CC_APPINFO;
    While i can query "ULTBPM_CCHK"."ERKANDENE_V" without any problem, following errror occurs for "ULTBPM_CCHK"."ERKANDENE_V2":
    SELECT AL1.CCAI_RECORDDATETIME FROM ULTBPM_CCHK.ERKANDENE_V2 AL1
    ODBC Error: SQL API: [SQLBindCol], SQL RETURN: [-1], SQL STATE: [HY003], SQL NATIVE ERROR: [0], SQL MESSAGE: [[Microsoft][ODBC Driver Manager] Program type out of range]
    I want to select timestamp colum, Any sugestions?
    Hyperion Reporting Studio 9.3.1
    Oracle 9i clent
    Oracle 10g (10.2.0.4) database
    Regards,
    Erkan Saka

    Hi,
    This time it gives "ORA-03106: fatal two-task communication protocol error". I searched metalink and fould that this may be caused by incompatible SqlNet libraries or NLS settings between cklient and server. I checked NLS settings but did not solved the problem. In dbgprint file i saw that hyperion identified timestamp column (B) as ColType 0. Is it normal for timestamp column? Because when i look at the column properties in Reporting Studio, i see nothing in Item Type.
    SELECT DISTINCT COLUMN_NAME, '*', COLUMN_ID, DATA_TYPE, DATA_LENGTH,
         DATA_SCALE, DATA_PRECISION, NULLABLE, '*' FROM SYS.ALL_TAB_COLUMNS
         WHERE TABLE_NAME = 'ERKAN_DENE' AND OWNER = 'DISBANK' ORDER BY
         COLUMN_ID
    Server Column Information
    ColName ColNum ColType Length Places Digits Nulls
    ======= ====== ======== ====== ====== ====== =====
    A 1 NUMBER 22 0 10 0
    B 2 TIMESTAMP(6) 11 6 10 1
    End Select
    DaMgr DMTable Column Information
    ColName ColNum ColType Length Places
    ======= ====== ====== ====== ======
    A 0 4 22 0
    B 1 0 11 6
    Begin Executing Document OnPreProcess Script.
    End Executing Document OnPreProcess Script.
    Begin Select
    (0 0 )
    Sending SQL to the Server:
    SELECT AL1.B FROM DISBANK.ERKAN_DENE AL1
    Oracle error -1 3106: ORA-03106: fatal two-task communication protocol error
    Exception thrown in v1_bi_code\bl\da\dasnet_l.cpp, line 959: Oracle Error -1: ORA-03106: fatal two-task communication protocol error
    DaSession::CancelOk()
    Regards,
    Erkan

  • Controlling the sort order for a column?

    I have a column which uses strings that I want to sort on. But, I don't want to do simple string sorting. Can I effect the sort order somehow? Maybe enumerate the values and assign integers to them?
    For example, I want to use Low, Medium, and High. Or maybe: L-, L, L+, M-, M, M+, H-, H, H+
    Any pointers on how to do this?

    Todd,
    Not knowing what you're trying to sort, it is difficult to make specific suggestions. Basically, two approaches come to mind. 1) start the lines of the column you want to sort with some type of sort code or 2) place that sort code in another column and sort on two columns - possible hiding the one with the codes.
    The next problem is designing a code that fits your situation. In the example you gave something like 1L-,2L,3L,...,8H,9H may work because there are only 9 categories. If more than 9, two digit numbers may work but remember to use leading zeros to pad single digit numbers.
    The code could also be alpha characters with relevance such as "Auto", "Clot", "Food", "Hous", "Misc", etc. But again, if these alphabetic categories are not in the order you like you may have to precede them with some sequence device to get what you want. Maybe something like "aFood", "bClot", "cHous", etc. would work. Designing a code applicable to a given situation that one can easily remember is not always easy.
    Hope this gives to something to think about and if you care to give more details you'll surely get some specific suggestions.
    pw

  • Sorting Timestamp Column in Datagid

    HI All,
    How can we Sort the TimeStamp Column (Ex: containing
    02/05/2007 16:44:03) in a DataGrid. Please help me
    Thanks a lot
    PSamanth

    have a look at the sortCompareFunction property of
    DataGridColumn component. This property allow you to define a
    callback for sorting a given column. Sort it the way you like in
    your function!
    Of course, the easiest way would be to part the string as
    Date object and use it's comparison methods.
    ATTA

  • Doubt in Timestamp column

    Hi,
    In below Query i am trying to retrive the data
    ,which is greater then the 18-DEC-10,
    But its retriving all the datas,why? please help.how to handle this time stamp column?
    desc vcps_misc_ch
    Name Null Type
    ENT_NM NOT NULL VARCHAR2(30)
    ATRBT_NM NOT NULL VARCHAR2(30)
    TXN_TYPE NOT NULL CHAR(1)
    TXN_DT NOT NULL TIMESTAMP(6)
    PREV_VALUE VARCHAR2(4000)
    CURR_VALUE VARCHAR2(4000)
    LAST_UPDT_GMIN VARCHAR2(9)
    LAST_UPDT_NM VARCHAR2(4000)
    REF_ID NOT NULL VARCHAR2(2000)
    SELECT txn_dt,to_char(txn_dt,'dd-mon-yy hh24:mi:ss')
    FROM vcps_misc_ch
    WHERE to_char(txn_dt,'dd-mon-yy hh24:mi:ss') > TO_CHAR(TO_date('18-DEC-10','DD-MON-YY'),'dd-mon-yyyy hh24:mi:ss')
    and rownum<10
    TXN_DT TO_CHAR(TXN_DT,'DD-MON-YYHH24:MI:SS')
    26-FEB-10 01.14.43.055154000 PM 26-feb-10 13:14:43
    25-MAR-10 05.23.35.601172000 PM 25-mar-10 17:23:35
    26-MAY-10 08.12.40.106995000 AM 26-may-10 08:12:40
    27-MAY-10 10.38.32.033523000 AM 27-may-10 10:38:32
    28-MAY-10 11.40.23.313450000 AM 28-may-10 11:40:23
    28-MAY-10 01.09.52.332828000 PM 28-may-10 13:09:52
    18-JUN-10 02.44.37.614339000 PM 18-jun-10 14:44:37
    18-JUN-10 02.46.47.141109000 PM 18-jun-10 14:46:47
    24-JUN-10 10.45.43.814528000 AM 24-jun-10 10:45:43
    9 rows selected

    Hi,
    Always compare TIMESTAMP columns to other TIMESTAMPs.
    To compare a TIMESTAMP column to a value that is being supplied as a string, convert the string to a TIMESTAMP, not the other way around. It's more efficient, and less prone to error.
    For example:
    SELECT      txn_dt
    ,     to_char (txn_dt,'dd-mon-yy hh24:mi:ss')
    FROM      vcps_misc_ch
    WHERE      txn_dt     >= TO_TIMESTAMP ( '18-DEC-2010 14:45:00'
                        , 'DD-MON-YYYY HH24:MI:SS'
    ;or
    SELECT      txn_dt
    ,     to_char (txn_dt,'dd-mon-yy hh24:mi:ss')
    FROM      vcps_misc_ch
    WHERE      txn_dt     >= TO_TIMESTAMP ( p_date
                        , 'DD-MON-YYYY HH24:MI:SS'
    Do not nest conversion functions (such as "TO_CHAR ( TO_TIMESTAMP ...)").  There's almost always a simpler, more efficient way.
    TO_CHAR is appropriate for displaying a date (as in the SELECT clause above).  If you're tempted to use TO_CHAR for any other purpose (in a WHERE clause, for example), ask yourself why.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Importing timestamp columns appears to use to_date instead of to_timestamp

    I'm trying to import data (using the latest version 1.5.4 with Patch 2 applied) to an Oracle 10g database that contains timestamp columns. The input data has times with fractional (millisecond) values The data was exported using SQL Developer from a Sybase database and the timestamp format in the Excel (xls) file is YYYY-MM-DD HH24:MI:SS.FF3. When I specify this format for the TIMESTAMP columns on the import screens, the importer generates an insert statement like this:
    INSERT INTO A (TMS) VALUES (to_date('2008-12-049 12:12:39.967', 'YYYY-MM-DD HH24:MI:SS.FF3'));
    This command fails to execute with this error:
    Error report:
    SQL Error: ORA-01821: date format not recognized
    01821. 00000 - "date format not recognized"
    *Cause:   
    *Action:
    I found that if to_timestamp is used instead of to_date, there is no issue inserting the row with the correct time precision. The question I have is why isn't SQL Developer using to_timestamp for importing a TIMESTAMP column, and should it?
    Any advise woudl be appreciated.
    Thanks

    In 1.5.4 I see a bug where the "Format" field doesn't show up in the page in the import wizard, preventing the user from entering a mask when the column type is TIMESTAMP. This has been fixed in the code line under development and should be available when 2.1 gets released.
    To give you a bit more detail on the confusing DATE/TIMESTAMP behaviour...
    SQL Developer misrepresenting date as timestamp and vice versa stems from the behaviour of the Oracle JDBC driver. Following are the details I obtained from the JDBC team when I raised a bug("WRONG VALUE RETURNED FOR GETCOLUMNTYPE FOR DATE COLUMN ") on them:-
    oracle.jdbc.mapDateToTimestamp is by default set
    to true to indicate reporting DATE column as TIMESTAMP type. To turn off, pass
    -Doracle.jdbc.mapDateToTimestamp=false" at the command line.
    To effect this option in SQL Developer, you can add an AddVMOption -Doracle.jdbc.mapDateToTimestamp=false
    A bit more history on the option:
    8i and older Oracle databases did not support SQL TIMESTAMP, however Oracle
    DATE contains a time component, which is an extension to the SQL standard. In
    order to correctly handle the time component of Oracle DATE the 8i and
    earlier drivers mapped Oracle DATE to java.sql.Timestamp. This preserved the
    time component.
    Oracle database 9.0.1 included support for SQL TIMESTAMP. In the process of
    implementing support for SQL TIMESTAMP we changed the 9i JDBC driver to map
    Oracle DATE to java.sql.Date. This was an incorrect decision since it
    truncates the time component of Oracle DATE. There was also a backwards
    compatibility problem trying to write java.sql.Timestamps to 8i databases.
    These are separate problems but we "fixed" both under the control of a single
    flag, V8Compatible. This flag was introduced in a 9.2 patch set.
    By default the flag is false. When it is set to false the driver maps Oracle
    DATE to java.sql.Date, losing the time component and it writes
    java.sql.Timestamps to the database as SQL TIMESTAMPS. When the flag is set
    to true the driver maps Oracle DATE to java.sql.Timestamp and writes
    java.sql.Timestamps to the database as Oracle DATEs.
    In 11.1 the V8Compatible flag was deprecated because it controlled Database
    8i compatibility which is no longer supported. The additional behavior it
    controlled, how SQL DATEs are handled, is controlled by a new flag,
    mapDateToTimestamp. In 11.1 setting V8Compatible will just set
    mapDateToTimestamp. This new flag only controls how SQL DATEs are
    represented, nothing more. This flag will be supported for the foreseeable
    future.
    Finally, the default value for V8Compatible is false in 9i and 10g. This
    means that by default the drivers incorrectly map SQL DATEs to java.sql.Date.
    In 11.1 the default value of mapDateToTimestamp is true which means that by
    default the drivers will correctly map SQL DATEs to java.sql.Timestamp
    retaining the time information. Any customer that is currently setting
    V8Compatible = true in order to get the DATE to Timestamp mapping will get
    that behavior by default in 11.1. Any customer that wants the incorrect but
    10g compatible DATE to java.sql.Date mapping can get that by setting
    mapDateToTimestamp = false in 11.1.
    About the only way to see the difference between mapDateToTimestamp settings
    is to call getObject on a DATE column. If mapDateToTimestamp is true, the
    default setting, the result will be a java.sql.Timestamp. If
    mapDateToTimestamp is false, then getObject on a DATE column will return a
    java.sql.Date.
    HTH
    Edited by: vasan_kps on Jun 12, 2009 2:01 PM

  • Concatenate multiple columns into one string

    Hello,
    I am using Oracle 11.2, how can I concatenate the value of multiple columns into one string with one SQL:
    create table testTb(classId number(5), classRoom varchar2(32));
    insert into testTb value(101, 'room101');
    insert into testTb value(101, 'room201');
    insert into testTb value(101, 'room301');
    insert into testTb value(202, 'room444');
    insert into testTb value(202, 'room555');
    I would like to generate the result as followings:
    Class 101 is in room101, room201, room301
    Class 202 is in room444, room555
    Thanks,

    Hi,
    Since you're using Oracle 11.2, you can use the aggregate LISTAGG function:
    SELECT       'Class ' || classid
                   || ' is in '
                 || LISTAGG ( classroom
                         ) WITHIN GROUP (ORDER BY classroom)
                   AS txt
    FROM       testtb
    GROUP BY  classid
    ;The generic name for concatenating all the strings in a group is String Aggregation . This page shows several ways to do it, suitable for different versions of Oracle.

  • Parse column with csv string into table with one row per item

    I have a table (which has less than 100 rows) - ifs_tables that has two columns: localtable and Fields. Localtable is a table name and Fields contains a subset of columns from that table. Fields is a comma delimited list:  'Fname,Lname'. It looks like
    this:
    localtable         fields
    =========  =============
    customertable   fname,lname
    accounttable     type,accountnumber
    Want to end up with a new table that has one row per column. It should look like this:
    TableName             ColumnName
    ============ ==========
    CustomerTable        Fname
    CustomerTable        Lname
    AccountTable          Type
    AccountTable          AccountNumber
    Tried this code but have two issues (1) My query using the Splitfields functions gets "Subquery returned more than 1 value" (2) some of my Fields has hundreds of collumns in the commas delimited list. It will returns "Msg 530, Level 16, State
    1, Line 8. The statement terminated. The maximum recursion 100 has been exhausted before statement completion.maxrecursion greater than 100." Tried adding OPTION (maxrecursion 0) in the Split function on the SELECT statment that calls the CTE, but
    the syntax is not correct.
    Can someone help me to get this sorted out? Thanks
    DROP FUNCTION [dbo].[SplitFields]
    go
    CREATE FUNCTION [dbo].[SplitFields]
    @String NVARCHAR(4000),
    @Delimiter NCHAR(1)
    RETURNS TABLE
    AS
    RETURN
    WITH Split(stpos,endpos)
    AS(
    SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
    UNION ALL
    SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
    FROM Split
    WHERE endpos > 0
    SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
    'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
    FROM Split --OPTION ( maxrecursion 0);
    GO
    IF OBJECT_ID('tempdb..#ifs_tables') IS NOT NULL DROP TABLE #ifs_tables
    SELECT *
    INTO #ifs_tables
    FROM (
    SELECT 'CustomerTable' , 'Lname,Fname' UNION ALL
    SELECT 'AccountTable' , 'Type,AccountNumber'
    ) d (dLocalTable,dFields)
    IF OBJECT_ID('tempdb..#tempFieldsCheck') IS NOT NULL DROP TABLE #tempFieldsCheck
    SELECT * INTO #tempFieldsCheck
    FROM
    ( --SELECT dLocaltable, dFields from #ifs_tables
    SELECT dLocaltable, (SELECT [Data] FROM dbo.SplitFields(dFields, ',') ) from #ifs_tables
    ) t (tLocalTable, tfields) -- as Data FROM #ifs_tables
    SELECT * FROM #tempFieldsCheck

    Try this
    DECLARE @DemoTable table
    localtable char(100),
    fields varchar(200)
    INSERT INTO @DemoTable values('customertable','fname,lname')
    INSERT INTO @DemoTable values('accounttable','type,accountnumber')
    select * from @DemoTable
    SELECT A.localtable ,
    Split.a.value('.', 'VARCHAR(100)') AS Dept
    FROM (SELECT localtable,
    CAST ('<M>' + REPLACE(fields, ',', '</M><M>') + '</M>' AS XML) AS String
    FROM @DemoTable) AS A CROSS APPLY String.nodes ('/M') AS Split(a);
    Refer:-https://sqlpowershell.wordpress.com/2015/01/09/sql-split-delimited-columns-using-xml-or-udf-function/
    CREATE FUNCTION ParseValues
    (@String varchar(8000), @Delimiter varchar(10) )
    RETURNS @RESULTS TABLE (ID int identity(1,1), Val varchar(8000))
    AS
    BEGIN
    DECLARE @Value varchar(100)
    WHILE @String is not null
    BEGIN
    SELECT @Value=CASE WHEN PATINDEX('%'+@Delimiter+'%',@String) >0 THEN LEFT(@String,PATINDEX('%'+@Delimiter+'%',@String)-1) ELSE @String END, @String=CASE WHEN PATINDEX('%'+@Delimiter+'%',@String) >0 THEN SUBSTRING(@String,PATINDEX('%'+@Delimiter+'%',@String)+LEN(@Delimiter),LEN(@String)) ELSE NULL END
    INSERT INTO @RESULTS (Val)
    SELECT @Value
    END
    RETURN
    END
    SELECT localtable ,f.Val
    FROM @DemoTable t
    CROSS APPLY dbo.ParseValues(t.fields,',')f
    --Prashanth

  • Max value for a TIMESTAMP column?

    What is the max value for a TIMESTAMP column?
    I'm using the ODP.NET provider 9.2.0.4. When i put C#'s DateTime.MaxValue (i.e. 12/31/9999 23:59:59,999) into a TIMESTAMP column, everything is ok. Retrieving this value (e.g. via SQL*Plus Worksheet) returns ora-01877 (string too long for internal buffer).
    Any ideas?
    Regards,
    Daniel

    Maybe you hit Bug 1782816 Select of TIMESTAMP gives ORA-1877 on some platforms
    Product (Component)                      : SQL*Plus (SQL*Plus)
    Range of versions believed to be affected: Versions >= 9.0 but < 9.2 
    Versions confirmed as being affected     : 9.0.1.3
    Platforms affected                       : Generic (all / most platforms affected)

  • Get millisecond values from timestamp column in v$logmnr_contents

    Hello
    How do we get millisecond values from timestamp column in v$logmnr_contents.
    I tried with following query.
    select scn,To_Char(timestamp,'DD-MON-YYYY HH24:MI:SS:FF') from v$logmnr_contents WHERE OPERATION NOT IN('START') and username ='SCOTT' and sql_redo is not null and (seg_owner is null or seg_owner not in('SYS'));
    it says ORA-01821: date format not recognized. I want to find the relation of scn with timestamp. In forums i found, scn is derived from timestamp value. I dont know its correct or not.
    if i query with out FF in time format i get like
    scn timestamp
    808743 27-NOV-2007 00:12:53
    808743 27-NOV-2007 00:12:53
    808743 27-NOV-2007 00:12:53
    808744 27-NOV-2007 00:12:53
    808744 27-NOV-2007 00:12:53
    808744 27-NOV-2007 00:12:53
    if scn is derived from timestamp with milliseconds, each scn should be different right?More help please

    May be there's an easy way solving your problem, I did it like that:
    CREATE TABLE quota_test (test VARCHAR2(50))
    INSERT INTO quota_test
    VALUES ('update "SCOTT"."NEWTAB1" set a="34" and b="45"')
    SELECT test normal, REPLACE(SUBSTR(test,INSTR(test,'"',1),INSTR(test,'.',1)+2),'"','') changed
    FROM quota_test
    Result is :
    NORMAL
    update "SCOTT"."NEWTAB1" set a="34" and b="45"      
    CHANGED
    SCOTT.NEWTAB1
    If you didn't understand, I can explain what I wrote

  • How to create a default value of timestamp column?

    I am trying to create a table with a default value on a timestamp column, can it be done?
    CREATE TABLE myTbl
    FutureDateTime date default TIMESTAMP WITH TIME ZONE '2999-12-31 23:23:59.000'
    )

    user1035690 wrote:
    I am trying to create a table with a default value on a timestamp column, can it be done?
    CREATE TABLE myTbl
    FutureDateTime date default TIMESTAMP WITH TIME ZONE '2999-12-31 23:23:59.000'
    )Yes, but you don't have a timestamp column, you have a date column.
    CREATE TABLE myTbl
       FutureDateTime date default to_date('2999-12-31 23:23:59', 'yyyy-mm-dd hh24:mi:ss')
      4  );
    Table created.
    Elapsed: 00:00:00.09
    ME_XE?And just in case you weren't aware, storing "end of time" information like this will be rough on your queries (it skewes the cost based optimizers estimates for cardinalities and could wildly throw off the estimates for your queries, resulting in bad plans). You're better off to store NULL values, NULL denoting not known values.
    Just an FYI :)

  • How i pass table column  value to string variable or return to java applete

    Hi Master,
    How do I pass a table column value into string variable. See my code below:
    import java.sql.*;
    public class Waheed {
    public Waheed() {
    public static void main (String args [])
    String s = "9 23 45.4 56.7";
    System.out.println ("going for connection");
    // DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
    try{
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn =
    DriverManager.getConnection("jdbc:oracle:thin:@fahim:1521:aamir","muhammad","mfa786");
    Statement stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery("select accid from accbal");
    System.out.println ("going for connection");
    while (rset.next())
    s= rset.getString("accid"); this line give me error
    System.out.println (rset.getString("accid"));
    System.out.println (s);
    catch(Exception e){
    e.printStackTrace();
    This line give me an error:
    s= rset.getString("accid");
    s is string variable
    Plese give me an idea how I can pass accid in s variable.
    Thanks.
    Aamir

    See the code sample in the following thread (try using upeercase).
    JDBC  connection
    Kuassi

Maybe you are looking for

  • Compatibilty mode for itunes in windows vista

    when i start itunes a get a message saying itunes compatibilty mode is set for an earlier version of windows. i went to itunes application hit properties then compatibility tab and unchecked the box for compatibilty mode but i still get the same mess

  • Transferring files between iMac and Mac Air

    My daughter gifted me a new but older Mac Air (mid 2011). I tried to transfer files from my existing iMac (2008) to Mac Air using migration assistant, but the connection never happens. What am I doing wrong?

  • Using CVS in SQL Developer for Data Modeler changes.

    Hi, I am fairly new to SQL Developer Data Modeler and associated version control mechanisms. I am prototyping the storage of database designs and version control for the same, using the Data Modeler within SQL Developer. I have SQL Developer version

  • HOST Solution

    Host Command usages in Forms6i (OS Win-2000): HOST('RunBrowser http://www.hotmail.com', NO_SCREEN); PS: You may need to copy RunBrowser.exe from "Oracle Forms and Reports Demos" CD to ORALCE_HOME/Bin directory. Hope this will work for you! Jagannath

  • Handling exceptions for a event handler method.

    Hi Mates,                 I have two custom container in which i am displaying an alv grid usind objects. when a double click event is performed in one of the alv the other alv should be displayed. I now have to handle exceptions of the class  CX_SY_