SQL - transform a date string

Hello,
I have scenario where I need to transform a date string in SQL (from "yyyy-mm-dd" to "dd/mm/yyyy"):
E.g My table EMPTABLE looks like this
EMPNO STARTDATE(string)
1111 2000-11-30
2222 1998-01-22
I need an output of
EMPNO STARTDATE(string)
1111 30/11/2000
2222 22/01/1998
I know that we can user "to_date" and "to_char" functions to do that. The query would look like:
SELECT EMPNO as EMPNO, to_char(to_date(STARTDATE,'yyyy-mm-dd'),'mm/yy/dddd') as STARTDATE from EMPTABLE;
Are there any other ways to achive this? Like just using string manipulation.
Why I'm asking with the above query if there is any data discrepancy (e.g for one record the month value is 25 by mistake), the query fails.
Any help is appreciated.
Thanks.
Edited by: kIDMan on Nov 20, 2009 7:29 AM

Hi,
Welcome to the forum!
A lot of folks store dates in DATE columns; then it just takes one TO_CHAR call to get them in any format, and invalid data is impossible.
You can use SUBSTR to extact parts of the string, and || to re-assemble them in a different order.
Starting in Oracle 10, you can also use regular expressions, like this:
,     REGEXP_REPLACE ( startdate
                        , '([0-9]{4})-'     ||     -- \1 = year
                              '([0-9]{2})-'     ||     -- \2 = month
                   '([0-9]{2})'          -- \3 = day
                        , '\3/\2/\1'
                        )          AS startdate_dmyIf startdate does not contain the pattern (4 digits, hyphen, 2 digits, hyphen, 2 digits), the the expression above will return startdate unchanged.
Edited by: Frank Kulash on Nov 20, 2009 1:11 PM

Similar Messages

  • Date format in Apply SQL Transformation

    I'm trying to read data from an Azure SQL database to an ML Studio experiment and do a SQL transformation on it. 
    The data has a DateTime column in the following format: YYYY-MM-DDTHH:MM:SS.SSS, but as it gets passed to the Apply SQL Transformation module it somehow changes into the 12-hour format: DD/MM/YYYY HH:MM:SSAM/PM
    This means that I cannot use the strftime()-function in the SQL module. Any way to get around this?

    We're working on fixing the DateTime handling in SQL module. Meanwhile you can try the following workaround:
    1) Before using Apply SQL module, convert dates into strings with format “yyyy-mm-dd” that SQLite can parse.
    2) Use SQLite date() function to convert those strings back to dates
    The step 1) can be accomplished using Execute Python module (here “DateTime” is the name of column with dates), for example:
    import datetime as dt
    import pandas as pd
    def azureml_main(dataframe1 = None, dataframe2 = None):
        c= dataframe1['DateTime']
        cs = []
        for elem in c:
            cs.append(str(dt.date.fromtimestamp(elem)))
        return pd.DataFrame({"DateTime":cs}),
    The SQL script in step 2 would look like, for example:
    select * from t1 where date(t1."DateTime") < "2005-07-25" ;

  • Msg 0, Sev 0, State 1: Unknown token received from SQL Server [SQLSTATE HY000] String data, right truncation [SQLSTATE 01004] [SQLSTATE 08S01] error

    I'm looking for some general guidance on this complete error:
    Msg 0, Sev 0, State 1: Unknown token received from SQL Server [SQLSTATE HY000]
    String data, right truncation [SQLSTATE 01004]
    Msg 16389, Sev 16, State 1: The connection is no longer usable because the server response for a previously executed statement was incorrectly formatted. [SQLSTATE 08S01]
    This error is caused by a SQL Agent Job, but it does not always occur. I understand this could be an issue with SQL dropping the connection, but what is the best way to troubleshoot this?
    Thanks,
    Phil

    Hi philliptackett77,
    It would be more helpful for troubleshooting the issue if you post the SQL Server error log and SQL Server version. Additionally, please state what purpose of using the agent job.
    Based on my research, [SQLSTATE 08S01] error means communication link failure. If the executed statement returns invalid value in the job, the connection between server and client will fail. This error could be caused by the error of [SQLSTATE HY000] and
    [SQLSTATE 01004]. I’d like to share my knowledge about these errors as below.
    Quote: String data, right truncation [SQLSTATE 01004]
    This error could occur when passing data whose length is larger than the received object,and the passed value is truncated, and returns invalid value. So please check if the data type of the objects are identical and the length of passed value is not larger
    than the received object.
    Quote: Msg 0, Sev 0, State 1: Unknown token received from SQL Server [SQLSTATE HY000]
    The error could occur in the two cases below.
    1. If you use SQL Server version 6.50, and execute the cursor in the job step, set the statement options to use a server-side cursor and prepare a select statement on a SQL Server system table. The first execution of the select creates the cursor successfully.
    After you close this cursor, if you execute the prepared statement again, the error could occur.
    I recommend you to apply the latest service pack firstly. If the error still occurs, you could change your code by using a forward-only cursor instead of a static, keyset, or dynamic cursor on the system tables. If a forward-only cursor is unacceptable,
    prepare the select statement again on the system table and execute it to create a server-side cursor. For more information about the process, please refer to the article:
    http://support.microsoft.com/kb/151693/en-us
    2. The TDS stream from the server is invalid when transfer data between a database server and a client. This error is typically caused by a problem on the server. For more information about errors above, please refer to the article:
    http://technet.microsoft.com/en-us/library/aa937531(v=sql.80).aspx
    Regards,
    Michelle Li

  • SQL DM - Data Transformation and Data Movement option ?

    SQL DM - Data Transformation and Data Movement option ?
    I am using SQL DM 3.0.0.665. I need your thoughts on following.
    We find that Erwin introduced Data Transformation and Data Movement functionality to support ETL need. We were able to generate ETL spec using this feature.
    Does SQL DM have any plan to introduce such features?
    How do we use the current SQL DM to build ETL spec ?
    Thanks in helping us out.

    Hello,
    I am currently experimenting with SQL Data Modeler to produce high level solution designs and ETL specifications.
    Have not completed what I am doing but so far have come up with the following:
    Current assumption I am working on:
    All objects specified within the SQL Data Modeler will export to the Reporting Schema tables set up in an Oracle database. Once the data is within these tables then it will be a simple task to develop a SQL report to extract the data in any format required.
    1) There is nothing in the physical (Relational) Model section that supports this
    - though I have yet to fully use the Dimensional Modelling functionality which may have the mapping functionality required to specify an ETL
    2) We need diagrams of the processes as well as the ETL mapping
    - Process modelling is available in the Logical
    - Reverse Engineer all Physical objects to become Logical object i.e. one Table to one Entity
    - For each Entity set up an Information Structure
    (Currently this can only be done in a convoluted method via creating a diagram, creating a Flow and editing the Flow then drilling down)
    MESSAGE to SQL Data Modeler Support: Can things be set up so that Information Structures can be set up directly from the Browser, current method is a bit nonsensical
    - You are now set up to use the Logical Process Modeling functionality to capture the ETL requirements
    - Advise that you reference the training to understand what primitive, composite and transformation processes objects are
    - Also, take the time to understand what an external agent object is
    - Will assume you know what a Data Store is
    Here is the standard I am heading towards that seems feasible, will need to run a proof of concept within the larger team to ensure it works though:
    - A Logical is kept that is a one for one with the Physical
    (The only reason for this is that there is no process modeling functionality for the Physical objects
    MESSAGE to SQL Data Modeler Support: Can you duplicate the Process Modeling for the Logical to be available for the Physical objects too, would be a great help to specify ETL jobs.
    - An External Agent is used to represent an external source e.g. Billing application
    - A primitive process is used to represent the high Level design
    - A composite process is used to specify processes which can be further broken down to ETL jobs
    - A transformation process is used to represent an ETL job
    Within a Transformation process you can specify the mapping from multiple sources to a target table
    There are some negatives to this approach:
    - You lose the physical schemas the tables are part of, though a naming convention will get round this
    - You need to maintain a logical that is one for one with the physical, this is not a big overhead
    However, as I have stated in my message to the SQL Data Modeler support team, would all be resolved if the Process Modeling functionality were also made available within the Physical objects environment.
    Please note that we have not as yet adopted the above approach and are still assessing is SQL Data Modeler will meet this requirement to our satisfaction. The critical bit will be if the data exports to the Reporting Schema, if it does then we have plenty of SQL resource that can produce the reports required procided the data can be captured.
    Hope that all helps.
    Also, hope I have not missed the point of your email.
    Kind regards,
    Yusef

  • Problems in SQL transform with variable in statement

    Hi,
    I have an sql transform with a variable in the statement. It looks like this:
    SELECT * FROM I.X where I.X.CUSTOMERNUMBER IN ([$variable])
    I have a script running prior which sets the $variable = '\'366800\',\'000933\'';
    (the CUSTOMERNUMBER field is a string)
    The problem is when DI compiles the SQL with the variable value, it is replacing each single quote with two single quotes, and thus turning my list of values into a single string (as recognised by DB2).
    How can I work around this? The CUSTOMERNUMBER field is indexed and the table is very large, so I want to use a very efficient statement to retrieve the data. I'm inserting this data into a different database, so I can't use the sql() function to execute the query and insert the rows into a new table in the same database (don't have authority to do that).
    I also need the sql to be dynamic because the customer numbers required will change from time to time. They're listed in another database and I plan on writing a loop to set the $variable value to contain all values in the lookup table, but I can't use that in a join because its in a different database and would not be efficient.
    Does anyone have any ideas? I'm literally all out, have tried a wide range of things to no avail, and none of my colleagues can work it out either.
    Thanks very much,
    -Steve

    I assume the SQL Transform is used only because of that in-list, not for other reasons....
    In this book page here: https://boc.sdn.sap.com/node/20046 at the very bottom it isdescribed on how to use the pushdown_sql() function in a where clause to add *any* text of your choice into the select statement DI generates. In this example I used a "where exists" but you can easily change the text to
    where key=5 and       pushdown_sql('my_datastore', 'CUSTOMERNUMBER IN ([$variable])')    and gender='M'
    I used the key=5 and gender=M just to clarify the syntax (I hope).
    For the SQL Transform, I wonder if you need the [$variable] syntax as well....

  • ERROR [HY000] [DataDirect][ODBC Progress OpenEdge Wire Protocol driver][OPENEDGE]Invalid date string (7497) (pgoe1022.dll)

    I am selecting data from a Progress database using the Data Direct Open Edge 10.1.B driver. The target table stores the date values as varchar in this format "22-OCT-14" In the select statement I can use Progress statements or T-SQL to transform
    the varchar to a date - but cannot do the same in the WHERE clause 
    Select po_number, cast(po_date as date) as [po_date] from [po_table] 
    (no problem - the [po_date] field stored as "22-OCT-14" is returned as "2014-10-22 00:00:00"
    but when I include the cast in the where clause I get the error described in the title
    Select [po_number], [po_date] from [po_table WHERE cast([po_date] as date)<= '10/22/2014' - NO GOOD
    I have tried very many combinations of the date string format , different functions and sub-queries but cannot find an answer

    The sql strings I posted are working examples - I've tried the ISO format you included - any number of date formats will work when the target field is a "Date" field - but trying any kind of transform statment to processa date stored
    as a varchar in the WHERE CLAUSE throws the erro
    Storing dates in a varchar column is a bad idea on any platform. Apparently there are strings in that column which cannot be converted to dates.
    On SQL Server you could have found this with
    SELECT po_date FROM po_table WHERE isdate(po_date) = 1
    What you should use on Progress, I have no idea.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • SQL Transform with VARIABLE

    Hello!
    I have the SQL Transform with global variable.
    First, I have a script for iniciality the variable:
    $DATE_CUST= to_date('2011/11/15 00:00:00.000','YYYY/MM/DD HH24:MI:SS.FF');
    I print the variable, in the execution write:
    2800     896     PRINTFN     2011.11.15 00:00:00.000000000
    STEP in SQL Transforms: 
    1.  SELECT * FROM TABLE_CUSTOMER
    2.  PUSH the update Schema button
    3.  add the where clause:  WHERE DATE_CUSTOMER > [$DATE_CUST]
    4.  save the DataFlow.
    When the execute the job, But we got error...  The variable is null or empty
    In the log trace: 
    |Data flow DF_VAR|Reader SQL
    SELECT query <select * from TABLE_CUSTOMER
    WHERE DATE_CUSTOMER  > 
    The database error message is <Sybase SQL Server <CRMGCPSA> error message for operation <ct_results>: <Sybase ASE Server message number <102> State <1> Severity <15> From Server <ASEDWHD>:   Message Text is: Incorrect syntax near ')'.
    >.
    Why no have value the variable ?
    The script correct should be
    SELECT query <select * from TABLE_CUSTOMER
    WHERE DATE_CUSTOMER  >  2011.11.15 00:00:00.000000000

    Both braces and square brackets can be used to reference variables, however they behave slightly differently.
    suppose I have the following hard-coded SQL statement
    select * from al_funcinfo where name = 'avg'
    Now I want to make it dynamic, I can use a variable and some square brackets
    select * from al_funcinfo where name = '[$G_Name]'
    or braces
    select * from al_funcinfo where name = {$G_Name}
    As you can see, braces adds single quotes around the varible value.  It is very useful when constructing complex statements requiring string values to be delimited with quotes (as most SQL DBs do).  These variable interpolation techniques can be used in scripts.
    M

  • How to compare result from sql query with data writen in html input tag?

    how to compare result
    from sql query with data
    writen in html input tag?
    I need to compare
    user and password in html form
    with all user and password in database
    how to do this?
    or put the resulr from sql query
    in array
    please help me?

    Hi dejani
    first get the user name and password enter by the user
    using
    String sUsername=request.getParameter("name of the textfield");
    String sPassword=request.getParameter("name of the textfield");
    after executeQuery() statement
    int exist=0;
    while(rs.next())
    String sUserId= rs.getString("username");
    String sPass_wd= rs.getString("password");
    if(sUserId.equals(sUsername) && sPass_wd.equals(sPassword))
    exist=1;
    if(exist==1)
    out.println("user exist");
    else
    out.println("not exist");

  • Connect to MS SQL Server 2000 data warehouse

    Hi,
    I use a MS SQL Server 2000 database for my web application where I use JSP. I suppose to create data warehouse using MS SQL Server's Data Transformation Service. But I don't know it's possible to connect to a MS SQL Server's data warehouse using JSP. So I want to know is it possible to connect to data warehouse using JSP and if it is how to do it? Thank you.

    You can certainly connect to M$ SQL Server using the JDBC driver:
    http://www.microsoft.com/downloads/details.aspx?FamilyID=4f8f2f01-1ed7-4c4d-8f7b-3d47969e66ae&displaylang=en
    Connecting to a data warehouse is no different from any relational database. (My understanding is that a data warehouse usually means a star schema implemented in a relational database.) This will connect you.
    If you're not familiar with JDBC, you might need the tutorial:
    http://java.sun.com/docs/books/tutorial/jdbc/

  • Writing a stored procedure to import SQL Server table data into a Oracle table

    Hello,
    As a new DBA I have been tasked with writing a stored procedure to import SQL Server table data into an Oracle table. I have been given many suggestions on how to do it from SQL Server but I I just need to write a stored procedure to run it from the Oracle side. Suggestions/guidance on where to start would be greatly appreciated! Thank you!
    I started to write it based on what I have but I know this is not correct :/
    # Here is the select statement for the data source in SQL Server...
    SELECT COMPANY
    ,CUSTOMER
    ,TRANS_TYPE
    ,INVOICE
    ,TRANS_DATE
    ,STATUS
    ,TRAN_AMT
    ,CREDIT_AMT
    ,APPLD_AMT
    ,ADJ_AMT
    ,TRANS_USER1
    ,PROCESS_LEVEL
    ,DESCRIPTION
    ,DUE_DATE
    ,OUR_DATE
    ,OUR_TIME
    ,PROCESS_FLAG
    ,ERROR_DESCRIPTION
      FROM data_source_table_name
    #It loads data into the table in Oracle....   
    Insert into oracle_destination_table_name (
    COMPANY,
    CUSTOMER,
    TRANS_TYPE,
    INVOICE,
    TRANS_DATE,
    STATUS,
    TRANS_AMT,
    CREDIT_AMT,
    APPLD_AMT,
    ADJ_AMT,
    TRANS_USER1,
    PROCESS_LEVEL,
    DESCRIPTION,
    DUE_DATE,
    OUR_DATE,
    OUR_TIME,
    PROCESS_FLAG,
    ERROR_DESCRIPTION)
    END;

    CREATE TABLE statements would have been better as MS-SQL and Oracle don't have the same data types.
    OUR_DATE, OUR_TIME will (most likely) be ONE column in Oracle.
    DATABASE LINK
    Personally, I'd just load the data over a database link:
    insert into oracle_destination_table_name ( <column list> )
    select ... <transform data here>
    from data_source_table@mssql_db_link
    As far as creating the database link from Oracle to MS-SQL ... that is for somebody else to answer.
    (most likely you'll need to use an ODBC driver)
    EXTERNAL TABLE
    If the data from MS-SQL is in a CSV file, just use and external table.
    same concept:
    insert into oracle_destination_table_name ( <column list> )
    select ... <transform data here>
    from data_source_external_table
    MK

  • Converting to a date string

    I am running the following select statement into Oracle SQL Developer.
    Select I_NOTE_DESIGS.END_DATE AS ENDDATE
    However in my results the date hows as 01-APR-29.
    I was wondering if there is a way to convert this over to another date string ie: I would like the date in this column to show 2029-04-01. I am not bothered if the time comes out at the end, as I have a program which can delete that.
    Regards,
    Jon Ditchfield

    >
    Hi Jon, and welcome to the forums.
    I was wondering if there is a way to convert this over to another date
    string ie: I would like the date in this column to show 2029-04-01.
    I am not bothered if the time comes out at the end, as I have a program which can delete that.select to_char(to_date('01-APR-29', 'dd-MON-YY'), 'yyyy-mm-dd') from dual;
    select to_char(to_date('01-APR-29', 'dd-MON-YY'), 'yyyy-mm-dd hh:mm:ss') from dual;
    Please be sure to read the forum FAQ. Also, read the "sticky" thread by BluShadow at the
    top of the list of posts on the forum home page.
    Always give your version of Oracle - the answer can vary greatly with version - although
    not in this case.
    These forums are a great resource - you will get the maximum benefit from them
    if you follow the guidelines.
    HTH,
    Paul...
    Jon Ditchfield

  • Please HELP!!!  Issue w/ Transformation from date to dateTime type

    Hi Guys,
    I'm having a problem with converting date to dateTime. We have a webservice that contain dateTime type and the input is date type. Is there a simple way to convert/transform a date to dateTime format? Example date = "2009-09-12", need to convert to dateTime = "2009-09-12T00:00:00". Thanks for helping!!!

    For this specific situation you could also make use of the concat string funtion: concat(date, 'T00:00:00'). The result equals your dateTime format.
    Kind Regards,
    Andre

  • Regarding disabling the Pushdown SQL feature in Data Services

    Hi Experts,
    I have created a mapping using decode function for replacing the original values in legacy system to new SAP values specified. The mapping is showing no syntax errors, but while executing the job, it is saying that there are no sufficient priviliges in the source database to perform that query. That mapping query that I wrote is being pushed to source database where there are no sufficient priviliges to execute that query,
    Can you suggest me a way to disable that pushdown SQL feature so that I can be able to eliminate that error?
    Thanks in advance.

    Hi Manoj,
    The query that is getting pushed to database is the decode function used in the mapping to change the values. It is saying insuficient priviliges to execute it. I removed that mapping and kept in an SQL transform while fetching data from the source and it executed successfully. I didnt understand how it could execute the job successfully when I put the same mapping in the SQL transform rather than putting it in a Query transform.

  • Oracle date string parser

    I really want that oracle can change their command parser engine to be smart enough especially for date string parsing.
    currently the engine will throw error when we type a date string as (for example) '10/10/10', while this command can be accepted in MS-SQLServer.

    AMaster wrote:
    i have stored three numbers in three different variables and want to join all of them to concatanate:
    http://docs.oracle.com/cd/B19306_01/server.102/b14200/operators003.htm
    make a date string , kindly help me with this.
    Edited by: AMaster on Sep 6, 2012 4:12 AMto_date:
    http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions183.htm
    How to ask a question:
    SQL and PL/SQL FAQ

  • BOBJ DI 12.2.2.1| SQL Transform call stored procedure on MSSQL 2008 FAIL

    Hello everyone!
    Sorry for my bad english.
    in my job is one dataflow with sql transform, query and target table (LOG).
    SQL Text is :
    EXEC dbo.ProcName
    in this SP next content:
    BEGIN TRY
    CREATE TABLE #t(...)
    INSERT INTO #t SELECT (...)
    INSERT INTO Table1
    SELECT(...) FROM #t
    ENDTRY
    BEGIN CATCH
       SELECT (row with error number, error message)
    END CATH
      IF NOERROR SELECT (row with no error and rows affected)
    When I run it from Management Studio all is OK. Data is successfully inserted into Table1and rRow with rowcount was inserteg into LOG.
    But When I run it in Job on JobServer exact row inserting into LOG BUT! no data inserting into Table1. and rowcount is equal in both cases.
    What's happening?
    Help please.

    for calling a stored procedure from DI, SQL Transform is not the correct way of doing it, the better option is to import the stored procedure in SQL Server Datastore and calling in a script or in a mapping depending on what that SP is doing
    to import a stored procedure in a DataStore, expand the Datastore select function node and click Import by name, in the type select function and enter the stored procedure or function name
    for DI both Stored Procedure and Functions are treated as Functions

Maybe you are looking for

  • CDATA tag in xml

    Does anyone know if CDATA tag is supported for values.  For example can XI do the following; <vendor-name><![CDATA[MOON FREIGHT LINES, INC.]]></vendor-name> The vendor name value is "MOON FREIGHT LINES, INC." which is included in the CDATA tag.  Can

  • Working off a remote harddrive

    Please could someone tell me is it possible to keep all my photos on a remote harddrive and then organise, edit etc them using photoshop elements 4.0 on windows vista? Ideally i would like to work off my remote hard drive (with all the photos on) and

  • Send SRM Purchase order Cancellation request to Vendor using SAP PI

    Hi gurus, We have to build an interface to send Purchase order cancellation request to vendor once the PO is deleted in SRM using PI. Could some one please send me out a document to set up this interface. Thanks in advance for your help. Regards, Cat

  • Viewing options in Application Library

    I'm sorry if this is nothing new, but I didn't find anything good on it. Probably because there are so much threads here and the search doesn't help that much.. Anyway, I'm a little annoyed by the limited viewing option in the application library. Yo

  • USER TableSpace

    Hello, After I created an Oracle 9i database using Database Configuration Assistance, I noticed several tablespaces are created including SYSTEM, UNDO, and USER. I created one permanent and one temporary tablespaces of my own (TESTTB1, TESTTEMPTB1).