Solved

sql date conversion

Posted on 2014-09-17
10
192 Views
Last Modified: 2014-09-18
I have a table that we get from a vendor that has 2 columns

Here is a sample of the data

SDNUID      BirthDate
2674      10 Dec 1948
2683      1938
2687      May 1937
2607      Null


The Birthdate field is defined as varchar(50)

The field contains 'date' in one of 3 formats  (date could have a null value)

dd mmm yyyy

yyyy

mmm yyyy

What I would like to do is write a query that will return a valid date format by doing the following

if date value is in dd mmm yyyy format then return dd-mmm-yyyy

if date value is in yyyy format then return 01-01-yyyy

if date value is in mmm yyyy format then return 01-mmm-yyyy

if date value is null then return 01-Jan-1900

so using above data example

SDNUID      BirthDate
2674      10-Dec-1948
2683      01-Jan-1938
2687      01-May-1937
2607      01-Jan-1900

I thought of using case statement based on whether length of birthdate field is 11, 4, 8 or 0 but that didn't seem quite right
0
Comment
Question by:johnnyg123
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +2
10 Comments
 
LVL 13

Expert Comment

by:Russell Fox
ID: 40328505
The built-in CAST function will return the dates you want without mucking around with string parsing. You just need to work with the NULL value. That will leave you with a valid DATE field that you can format however you wish (see CONVERT(NVARCHAR...)):
SELECT SNUID, CAST(COALESCE(BDate, '1/1/1900') AS DATE) FROM YourTable

Open in new window

0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40328508
select SDNUID, replace(convert(varchar, cast(isnull(BirthDate, '1/1/1900) as datetime), 106), ' ', '-')
from yourTable
0
 
LVL 9

Expert Comment

by:macarrillo1
ID: 40328512
First, are you wanting to correct the data itself (update statements) or just query the data (select statements)?

If you are correcting the data, you can run a series of updates to address each of the anomolies.

For example:

Update TableName
Set BirthDate= 01-Jan-1900
Where BirthDate=NULL
0
Comparison of Amazon Drive, Google Drive, OneDrive

What is Best for Backup: Amazon Drive, Google Drive or MS OneDrive? In this free whitepaper we look at their performance, pricing, and platform availability to help you decide which cloud drive is right for your situation. Download and read the results of our testing for free!

 
LVL 40

Accepted Solution

by:
Kyle Abrahams earned 250 total points
ID: 40328514
Note I'm missing an apostrophe - corrected below:
select SDNUID, replace(convert(varchar, cast(isnull(BirthDate, '1/1/1900') as datetime), 106), ' ', '-')
from yourTable
0
 
LVL 69

Assisted Solution

by:Scott Pletcher
Scott Pletcher earned 250 total points
ID: 40329035
SELECT
    *,
   ISNULL(
        CASE WHEN BirthDate = 'Null' THEN NULL ELSE '' END +
        CASE WHEN BirthDate LIKE '[0-3][0-9] %' THEN LEFT(BirthDate, 2) ELSE '01' END + '-' +
        CASE WHEN BirthDate LIKE '%[A-Z][A-Z][A-Z]%' THEN SUBSTRING(BirthDate, PATINDEX('%[A-Z][A-Z][A-Z]%', BirthDate), 3) ELSE 'Jan' END + '-' +
        SUBSTRING(BirthDate, PATINDEX('%[12][0-9][0-9][0-9]%', BirthDate), 4)
        , '01-Jan-1900') AS New_Date
FROM (
    SELECT 2674 AS SDNUID,      '10 Dec 1948' AS BirthDate UNION ALL
    SELECT 2683,      '1938' UNION ALL
    SELECT 2687,      'May 1937' UNION ALL
    SELECT 2607,      'Null'
) AS test_data


Btw, given that you have to modify the data anyway, why not go to the universal format 'YYYYMMDD', which is unambiguous (regardless of dateformat settings), not language dependent, can be directly sorted without any conversion, and saves disk space?
0
 

Author Comment

by:johnnyg123
ID: 40330593
Thanks for all the posts!!!!

You wouldn't believe it (or maybe you would :-)) ....the requirement has changed slightly

Now I need to only capture valid dates and ignore any others

How would I query to return only those dates that are valid?

Using the sample data above, the query results would just be

2674      10 Dec 1948      

Thanks!
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 40330682
That's the other advantage of YYYYMMDD -- can be easily verified :-) .

Use ISDATE() on the value: if you get a 1 result, you can safely convert to a date/datetime.
0
 

Author Comment

by:johnnyg123
ID: 40330975
Thanks Scott..you pointed me in right direction

I was trying the isdate() of 1 in the query and was getting all rows because sql server thought that all 'dates' were valid

what I really wanted was only dates that were in ddmmmyyyy format so I used following in where clause

replace((BirthDate),' ', '-') = replace(convert(varchar, cast(isnull(BirthDate, '1/1/1900') as datetime), 106), ' ', '-')
0
 

Author Closing Comment

by:johnnyg123
ID: 40330980
Thanks!  Worked out great!
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 40331022
If ISDATE(<string>) returns 1, then CAST(<string> AS date|datetime) should always work correctly.  The only problem would be if you tried to do the conversion yourself, instead of letting SQL do it for you.
0

Featured Post

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SQL Lag Function DateDiff 2 26
sql server query 9 28
SQL query joining 6 tables in asp.net 4 34
Query Task 8 23
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

710 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question