Converting varchar to datetime where date field is missing

Hello Sir,
i have a column with varchar datatype values like '2013/12','2012/11' where date field is missing.  i want to convert it as datetime at runtime so that i can use datetime related function. Is it possible for ms sql server 2008?
thanking you.

>> I have a column with VARCHAR data type values like '2013/12', '2012/11' where DATE field is missing. I want to convert it as DATETIME2(0) at runtime so that I can use DATETIME2(0) related function. Is it possible for MS SQL Server 2008? <<
The most important leg on a three-legged stool is the leg that is missing :)  A DATE is made up of three fields; YEAR, MONTH and DAY. You gave no business rule for picking the DAY field, so this makes no sense. 
Since SQL is a database language, we prefer to do look ups and not calculations. They can be optimized while temporal math messes up optimization. A useful idiom is a report period calendar that everyone uses so there is no way to get disagreements in the DML.
The report period table gives a name to a range of dates that is common to the entire enterprise. 
CREATE TABLE Something_Report_Periods
(something_report_name CHAR(10) NOT NULL PRIMARY KEY
  CHECK (something_report_name LIKE <pattern>),
 something_report_start_date DATE NOT NULL,
 something_report_end_date DATE NOT NULL,
 CONSTRAINT date_ordering
  CHECK (something_report_start_date <= something_report_end_date),
etc);
These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantages are that it will sort with the ISO-8601
data format required by Standard SQL and it is language independent. The pattern for validation is '[12][0-9][0-9][0-9]-00-00' and '[12][0-9][0-9][0-9]-[01][0-9]-00' in the CHECK constraints. 
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • Converting varchar to datetime 103

    Hi Guys
    Im making a select query where in a colomn the date is yyyy-mm-dd, i need dd-mm-yyyy (103). A simple convert query does not work because the colomn is not set as a datetime but as a varchar. Its not possible to change the tables at the source.
    The colomn name is DATE_IN
    I think the following post could be helpfull but i dont know how to fix the given statements into the select query
    http://stackoverflow.com/questions/1509977/convert-varchar-into-datetime-in-sql-server

    > in a colomn the date is yyyy-mm-dd, i need dd-mm-yyyy (103)
    As suggested above, this is string date format to string date format conversion, purely string operations.
    If you convert to DATE / DATETIME first (universal internal binary representation), then it may fail if invalid date. 
    You can use the ISDATE or TRY_CONVERT functions to check if the string date is valid.
    DATETIME functions:
    http://www.sqlusa.com/bestpractices/datetimeconversion/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Converting Varchar to DateTime

    I need to convert a varchar column currently holding date and time to a proper datetime field.
    Example of the current view
    CRIS_Date
    05/02/2014 1130
    03/02/2014 1105
    05/02/2014 1145
    03/02/2014
    05/02/2014 0930
    After
    05/02/2014 11:30
    03/02/2014 11:05
    05/02/2014 11:45
    03/02/2014
    05/02/2014 09:30

    Another method with STUFF:
    You know, its not a good design storing your date time value in a varchar datatype. The best and first thing you should do is to change the varchar datatype to datetime datatype.
    create table #temp
    date_col varchar(100)
    insert #temp select '05/02/2014 1130'
    insert #temp select '03/02/2014 1105'
    insert #temp select '05/02/2014 1145'
    insert #temp select '03/02/2014'
    insert #temp select '05/02/2014 0930'
    Select date_col as 'before',case when len(rtrim(date_col))>10 then STUFF(date_col,14,0,':') else date_col end 'after' From #temp
    Drop table #temp

  • Not converting anything but get error: "Conversion failed converting varchar value 'X' to data type int"

    I have created the following trigger that fires instead of an UPDATE statement and copies the altered data over to an Audit table before proceeding with the requested UPDATE. After doing so, I wrote a simple UPDATE statement for testing:
    UPDATE Products
    SET ProductCode = 'XYZ 2014', ProductName = 'Special Edition Tamborine', ListPrice = 74.99, DiscountPercent = .5
    WHERE ProductID = 28;
    When I run this, I get the following message:
    Msg 245, Level 16, State 1, Procedure Products_UPDATE, Line 14
    Conversion failed when converting the varchar value 'X' to data type int.
    Here is my trigger:
    IF OBJECT_ID('Products_UPDATE') IS NOT NULL
    DROP TRIGGER Products_UPDATE; -- LINE 14
    GO
    CREATE TRIGGER Products_UPDATE
    ON Products
    INSTEAD OF UPDATE
    AS
    DECLARE @ProductID int, @CategoryID int, @ProductCode varchar, @ProductName varchar,
    @Description varchar, @ListPrice money, @DiscountPercent money, @DateUpdated datetime
    BEGIN
    SELECT @ProductID = ProductID, @CategoryID = CategoryID, @ProductCode = ProductCode,
    @ProductName = ProductName, @Description = Description, @ListPrice = ListPrice,
    @DiscountPercent = DiscountPercent, @DateUpdated = GetDate()
    FROM deleted;
    INSERT INTO ProductsAudit
    VALUES (@ProductCode, @CategoryID, @ProductCode, @ProductName, @ListPrice,
    @DiscountPercent, @DateUpdated);
    SELECT @ProductID = ProductID, @CategoryID = CategoryID, @ProductCode = ProductCode,
    @ProductName = ProductName, @Description = Description, @ListPrice = ListPrice,
    @DiscountPercent = DiscountPercent, @DateUpdated = GetDate()
    FROM inserted;
    UPDATE Products
    SET CategoryID = @CategoryID, ProductCode = @ProductCode,
    ProductName = @ProductName, Description = @Description,
    ListPrice = @ListPrice, DiscountPercent = @DiscountPercent
    WHERE ProductID = (SELECT ProductID FROM inserted)
    END
    I am confused a bit by (1) the location of the error and (2) the reason. I have looked over my defined data types and they all match.
    Could someone offer a second set of eyes on the above and perhaps guide me towards a solution?
    Thank you.

    This is an issue in this trigger. It will work for single record updates alone. Also for your requirement you dont need a INSTEAD OF TRIGGER at all.
    You just need this
    IF OBJECT_ID('Products_UPDATE') IS NOT NULL
    DROP TRIGGER Products_UPDATE;
    GO
    CREATE TRIGGER Products_UPDATE
    ON Products
    AFTER UPDATE
    AS
    BEGIN
    INSERT INTO ProductsAudit
    SELECT ProductID,
    CategoryID,
    ProductCode,
    ProductName,
    ListPrice,
    DiscountPercent,
    GetDate()
    FROM deleted;
    END
    Now, in your original posted code there was a typo ie you repeated the column ProductCode twice
    I think one should be ProductID which is why you got error due to data mismatch (ProductID is int and ProductName is varchar)
    see below modified version of your original code
    IF OBJECT_ID('Products_UPDATE') IS NOT NULL
    DROP TRIGGER Products_UPDATE; -- LINE 14
    GO
    CREATE TRIGGER Products_UPDATE
    ON Products
    INSTEAD OF UPDATE
    AS
    DECLARE @ProductID int, @CategoryID int, @ProductCode varchar, @ProductName varchar,
    @Description varchar, @ListPrice money, @DiscountPercent money, @DateUpdated datetime
    BEGIN
    SELECT @ProductID = ProductID, @CategoryID = CategoryID, @ProductCode = ProductCode,
    @ProductName = ProductName, @Description = Description, @ListPrice = ListPrice,
    @DiscountPercent = DiscountPercent, @DateUpdated = GetDate()
    FROM deleted;
    INSERT INTO ProductsAudit
    VALUES (@ProductID, @CategoryID, @ProductCode, @ProductName, @ListPrice,
    @DiscountPercent, @DateUpdated);
    SELECT @ProductID = ProductID, @CategoryID = CategoryID, @ProductCode = ProductCode,
    @ProductName = ProductName, @Description = Description, @ListPrice = ListPrice,
    @DiscountPercent = DiscountPercent, @DateUpdated = GetDate()
    FROM inserted;
    UPDATE Products
    SET CategoryID = @CategoryID, ProductCode = @ProductCode,
    ProductName = @ProductName, Description = @Description,
    ListPrice = @ListPrice, DiscountPercent = @DiscountPercent
    WHERE ProductID = (SELECT ProductID FROM inserted)
    END
    I would prefer doing it as former way though
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Crystal reports converting varchar 254 to memo data type

    Hi All,
    We are still using Seagate Crystal Reports 7.5 for some of our reporting. I have a problem that hopefully someone can help with. One of our connections is to ODBC- AR System ODBC Data Source.
    In that data source there are fields defined as varchar 254 (confirmed by DBA),
    But Seagate is calling them memo fields- which is causing problems since you canu2019t use memos in selection criteria or formulas.
    This happened after the field names were renamed. I noticed when the newly named fields were not showing as an option to map the old name fields to- because by default it looks for same data type, after unchecking same data type option the fields showed for mapping but wrong data type makes them useless. I canu2019t even convert them to string with formula field.
    Any input would be greatly appreciated.
    Thanks-

    Hi,
    Yup, this was a problem with versions prior to 10.  If a field was longer than 254 characters, Crystal handled them like Memos and you cannot use them in formulas.
    The only suggestion I can offer would be to upgrade.  Crystal can now use memos in formulas and no longer has a 254 character limit on strings.  So your charcter fields will remain as charater and not changed to Memos.
    Good luck,
    Brian

  • In OBIEE rpd convert varchar to datetime

    Hello,
    Can anyone help one how can we convert a column that is set to varchar to datetime in obiee;
    Suppose COLUMN_A is varchar and keeps value like '2008-12-30 10:11:22'
    and we want to convert it DATETIME.
    Thanks and Regards

    use cast(column as TIMESTAMP)

  • Value date field is missing in MIRO

    Hi Gurus,
    When I insert an account in transaction code MIRO, in tab "G/L account", the system shows the follwing message error: "An entry is required in Value date field for account XXXXXXXXXXX".
    I try to create a variant to display this field but it' s impossible.
    Could you please say me how I do?
    I would insert the value date in MIRO.
    BR.
    Thanks.
    Angela

    Hi Angela,
    there is an old SAP note available regarding your issue: 391683
    It seems the value date has been removed from the MIRO dynpros. (Nvertheless, when you try to change the layout and set value date fo visible, the length of the field is 0. So no use setting it to visible.)
    But you can activate the "Define default value date" in the Company code global data (T001). So for g/l accounts with required entry for value date, the value date is filled with the system date.
    Hope this helps.
    Best regards,
    Stefan

  • Business Partner Creation/Display - General Data fields are missing

    Hi,
    We have an issue in our ECC6.0 system. In FPP1/FPP2/FPP3 transactions General data fields such as Driver's license, SSN, Employee class are missing under Identification tab. But the same are displayed in BP transaction code. What configuration would causing this issue.

    I found a SAP Note 844949 which is talking about the same kind of issue. As per the note I regenerated subscreen containers for application object BUPA.
    Call transaction BUSP and generate the subscreen containers for the application objects BUPA, FICA and BUPR. To do this, set the "All screens" indicator under "Generate All Screens or Just Selected Screens".
    If this does not correct the incorrect display, use transaction BUPT for the business partner or transaction CAWM for the contract account to make sure that the fields are not missing due to the field modifications. (If you cannot call these transactions, exit the SAP Easy Access menu by using /n and then call BUPT or CAWM.

  • Date field is missing in the Table maintainance generator

    Hi,
      A table is created. A date field is there in that table. I tried to create a table maintainance generator for this table using 2 screens. Table maintainance generator is  created. But when I go to SM30 , I am unable to see this <b>DATE</b> field in the SM30 , in the first screen. But when I go to maintainance screen , I am able to see this field. This particularly happening with date field.
    Could you please help me.
    Regards,
    Satya

    go to se11 and type the table what you want.
    utilities, table maintenance generator.
    you config the options that you need.
    press F6 and go to sm30.
    its only this.
    Regards

  • Convert varchar to datetime in ssis

    hi,
    hox ca i convert  2012-09-20 08:50:05 which is in varchar(255) to a datetime 2012-09-20 00:00:00 with SSIS????

    Yes sure you can convert it very easily.
    using sql query:
    Declare
    @v varchar(255)
    Set
    @v =
    '2012-09-20 08:50:05'
    Select
    convert(datetime,@v)
    using SSIS:
    right click on source transformation -->go to advance editor --> click on tab input output properties -->oledb source output --> output column -->
    yourcolumnname --> on right you can see datatypes properties --> datatype --> change with database timestamp.
    Please Mark as Answer if my post solved your problem or Vote As Helpful if this helps. Blogs: www.sqlserver2005forum.blogspot.com

  • Failed to consume web service having datetime and date fields

    Hi everyone,
    We are trying to consume .net webservices which are exposed in SAP. But while cretaing proxy we having issues which is showing error shown below
    XSD date doesnot exactly corresponds to the ABAP type DATS
    XSD type dateTime does not exactly correspond to the ABAP type String.
    cheers
    ram

    Below is the code to add security header.
    public List<String> lookup(String lenderid, String url, String user, String pw) throws SOAPException { 
          SOAPHeader header = message.getSOAPHeader();
               if (header == null) {
                     header = envelope.addHeader();
                SOAPElement headerElement = createSecurityHeader(uName, pWord);
                soapHeader.addChildElement(headerElement);.................
    private static SOAPElement createSecurityHeader(String uName,String pWord) throws SOAPException {
           SOAPElement UsernameToken = null;
           SOAPFactory sFactory = SOAPFactory.newInstance();
           UsernameToken = sFactory.createElement("wsse:UsernameToken", "", WS);
           SOAPElement Username = sFactory.createElement("wsse:Username","", WS);
           Username.setValue(uName);
           UsernameToken.addChildElement(Username);
           SOAPElement Password = sFactory.createElement("wsse:Password","",WS);
           Password.setValue(pWord);
           QName qname = new QName("","Type");
           Password.addAttribute(qname,"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
           UsernameToken.addChildElement(Password);
           SOAPElement wsseSecurity = sFactory.createElement("wsse:Security","",WS);
           wsseSecurity.addChildElement(UsernameToken);
          return wsseSecurity;

  • Cannot convert varchar having milliseconds to date object

    Hi
    I tried to run this below query.
    select to_date('2009/04/06 07:29:29:2929 AM ','YYYY/MM/DD HH12:MI:SS:ssss AM ') from dual
    I am getting below exception
    ORA-01810: format code appears twice
    Can anyone please give me a solution for this
    Thanks
    RamG

    Hi
    Result of running the query select * from v$version
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    PL/SQL Release 10.2.0.4.0 - Production
    CORE     10.2.0.4.0     Production
    TNS for Linux: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    Thanks,
    Ram

  • Key fields and data fields re-arranged

    Hello SDN,
    Which design contains more records due to it showing more granularity? :
    1. ODS with more infoobjects assigned as Keys.
    2. ODS with less infoobjects assigned as Keys.
    assuming the total number of infoobjects remain the same.
    Where data fields can contain characteristics that can be used as keys or non-keys, depending on choice of design.
    My understanding is with more keys, less details available due to aggregation. Could you kindly help to confirm this is correct?
    I need to ask this because I am trying to change the re-arrange the keys by putting data fields as keys but not sure how this will turn out / behave.
    Thanks,
    Suzie

    Hi,
    <i>BUT! I cannot say that it will increase. That means, I think the record number remains the same!</i>
    I do not think that this is Right?
    for ex:
    1)
    Key fields:
    <i>Billing document</i>
    Data Fields
    <i>Sales Office
    Customer
    Net sales</i>
    So in the update rules , you can see the Overwrite for all Data fields. If the sales office is chaged for a record , the the OLD value will be over written by new value. So Before and after change to the records, the no of records are equal to 1.
    2)
    Key fields:
    <i>Billing document
    Sales Office</i>
    Data Fields
    <i>Customer
    Net sales</i>
    So in the update rules , you can see the Overwrite for all Data fields(now not for 'Sales Office'). If the sales office is chaged for a record , the the OLD value will not be over written by new value. It creates 2 records in Active table with respect to one change in new table.  So Before the change , the no of records was 1.now after change, the records' number becomes 3.
    With rgds,
    Anil Kumar Sharma .P

  • :Due On" date field missing while posting with Spl GL indicator for vendor

    Hello,
    I am facing a problen while posting a n entry with spl GL indicator in fb01, the issue is Due On date field is missing in the screen.
    I am posting an spl GL transaction for a vendor thro FB01 and after entering the posting key 39, vendor code and spl Gl indicator in line item and in next screen, the "Due ON" date field is not appearing.
    Both vendor recon account and spl GL alternative account use same field status group and  checked the field status group , the due date, payments terms are made optional.
    The strange thing is, when I use the same vendor with Spl GL indicator "A" , the Due ON field is missing in next screen, and when I use spl indicator " B" , for same vendor, Due On date field is appearing.
    Is there any specfic field status setting for DUE ON date field for Spl GL indicator wise? or please help me how to bring due on date field in the screen when posting spl GL transaction?
    Please help me on this.
    Regards
    Surya

    Hello Surya,
    To make field baseline date for payment (BSEG-ZFBDT) ready for input for
    posting the down payment, the following Customizing setting is
    necessary:
    Financial Accounting -> Accounts Receivable and Accounts Payable ->
    Business Transactions -> Outgoing Payments -> Automatic Outgoing Payment
    -> Payment Method/Bank Selection -> Configure payment program -> All
    company codes -> double-click on corresponding company code -> under
    Customer -> 'Sp. G/L transactions to be paid' the letter A should be
    entered.
    The field "Due On (BSEG-ZFBDT)" cannot be controlled with field status.
    It is contolled by field attribute of screen painter (Tcd: SE51).  If
    you look at element attribute for "Due On" field, a flag for required
    entry is activated.  In this case, field status has no control over
    the field.
    As of release 3.1G, field BSEG-ZFBDT is hardcoded in most FI screens
    to be mandatory and cannot be influenced by any field status
    changes. This situation is only valid when posting with special G/L
    indicator (ie PK 29/39).
    SAP development team has determined that this is a critical field.  The
    reason behind this is that this special GL screen and the data entered
    here are very important to many other programs. This data affects
    liabilities and receivables where due date is necessary almost
    everytime. Thus, we changed this field in this screen in order to
    prevent problems in many other areas. The reason is explained further in
    note 95079.
    545944    FAQ, down payment, tax code, baseline date
    above Field is controlled through SE51 only.
    Tcode : SE51
    Program (screen)     SAPMF05A
    Screen number        304
    Eliment list  press display.
    special attributes.
    BSEG-ZFBDT - Required.
    Other options are below.
         The attribute "Input" can have the following values:
         o    Not possible
             The input/output field cannot be supplied with an input - that
             the screen element can only be used for outputs.
         o   Possible
             The input/output field can be supplied with an input at runtime
             the remainder of the transaction, an input is not required.
         o   Recommended (Optional Field)
             The input/output field should be supplied with an input at runt
             The system, of course, does not check immediately whether there
             been an input. During the remainder of the transaction, however
             input is necessary.
             To mark this kind of target field, the input template starts wi
             special character that is represented in the Screen Painter by
             question mark ('?'). The question mark will be suppressed only
             the field is in a table control or a step loop.
             You use the "target field", for example, if inputs cover severa
             screens and only at a later stage are subject to a common check
    o   Required Field
        The input/output field must be supplied with an input at runtime.
        The system checks this property immediately, and very definitely
        when the event is processed  (PROCESS AFTER INPUT).
        So that such a required field is marked accordingly, its input
        template must begin with a special character that is represented in
        the Screen Painter by a question mark ('?'). The question mark is
        suppressed only if the field is in a table control or a step loop.
    I hope above information will resolve your issue.
    Kind Regards,
    Fernando Evangelista

  • Crystal Data Conversion Issue (Error converting data type varchar to datetime)

    Hi,
    I can run stored procedure without error in SQL Server using my personal credentials as well as database credentials.
    I can also run Crystal Report after connecting to Stored procedure without error on my desktop using my personal credentials as well as database credentials.
    But when I upload the crystal report in BOBJDEV and when I run using database credentials report fails saying that "Error in File ~tmp1d1480b8e70fd90.rpt: Unable to connect: incorrect log on parameters. Details: [Database Vendor Code: 18456 ]" but I can run the crystal report successfully on BOBJDEV using my personal credentials.
    I googled (Data Conversion Error Message) about this issue & lot of people asked to do "Verify Database" in Crystal Report. So I did that, but when I do it I am getting a error message like this:
    Error converting data type varchar to datetime.
    Where do you think the error might be occurring? Did anyone faced this kind of issue before? If so, how to resolve it?
    (FYI, I am using Crystal Reports 2008, & for stored procedure I have used SSMS 2012 )
    Please help me with this issue.
    Thanks & Regards.
    Naveen.

    hello Naveen,
    since the report works fine in the cr designer / desktop, we need to figure out where you should post this question.
    by bobjdev do you mean businessobjects enterprise or crystal reports server? if so please post this question to the bi platform space.
    -jamie

Maybe you are looking for

  • My itunes store won't work since upgrade to version 8.0

    My itunes store will not work since I upgraded to v8 I don't know what the problem is. Can someone please help me!!

  • IPad no longer recognized

    1st gen iPad not recognized by either computer after upgrading to iTunes 10.5. One is XP 32-bit and other is Win7 64-bit. Any solutions?

  • Adobe Acrobat XI Pro trial?

    I downloaded the trial (it took 5 hours and 500+mb) and there is nothing to indicate that the program is able to be activated.  I was not at the computer when the download finished and there were no error messages on the screen, it just took me back

  • HT201317 my photos are not automatically going to photo stream

    I have my husband's iPhone set up identical to my iPhone.  My photos are in photo stream but his will only stay in an album.  Phone problem or something else?

  • Podcast image missing

    After years of displaying correctly, my podcast image is now missing and seems to have been replaced by the default iTunes image in the iTunes store.  Here is the feed:  http://moneypit.com/show/moneypit_podcast.xml.  Would appreciate any suggestions