Solved

change date format

Posted on 2014-01-08
3
414 Views
Last Modified: 2014-01-09
I need to change the date format of a char(10) field to char(10) style 110. What is the most efficient way. This is sql 2005. Since the dates are consistent I suppose that I could use substring but is there a better way?

ex.05122008  change to  05-12-2008
0
Comment
Question by:qube09
3 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 500 total points
ID: 39766496
you would normally need a double conversion ... first from string to date, and then back.
http://www.experts-exchange.com/Database/Miscellaneous/A_1499-DATE-and-TIME-don%27t-be-scared-and-do-it-right-the-first-time.html

the issue is that the format ddmmyyyy is not a "known" style for the simple convert...
so, you have to first "rework" a bi the input string for this.

hence, you could as well "skip" the double conversion, and just do string operations:
update yourtable
  set yourfield = left(yourfield,2) + '-' + substring(yourfield, 3,2) + '-' + right(yourfield,4)
where yourfield like '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'

Open in new window


hope this helps
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 39766535
UPDATE dbo.tablename
SET date_column = STUFF(STUFF(date_column, 3, 0, '-'), 6, 0, '-')


For example:

SELECT date_column, STUFF(STUFF(date_column, 3, 0, '-'), 6, 0, '-')
FROM (
    SELECT '05122008' AS date_column
) AS test_data


Btw, odd format, since of course it won't sort correctly like that.
0
 
LVL 92

Expert Comment

by:Patrick Matthews
ID: 39767848
Why are you using char to store a date?

:)
0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

Suggested Solutions

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…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

840 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