Question

I am using SQL Server 2008 R2 and I have a field called StartDate in my tables that look like the following,

1977-10-17 00:00:00.000

how do I change those values to represent 10-17-1977? Also, if the date is 1900-01-01 00:00:00.000 I want to change it to null value. Is there a command or stored procedure for these types of changes?

thanks Nick

Was it helpful?

Solution 2

You will probably want to use convert to get the format you're after, as in:

select convert(varchar(10), MyColumn, 110) from MyTable;

Here we're converting your datetime to a character value, but with a particular date style (style 110).

Your null issue can be sorted with a case switch or with the nullif function:

select nullif(MyColumn, '19000101') from MyTable;
select case when MyColumn = '19000101' then null else MyColumn end from MyTable;

Note that I'm assuming MyColumn is stored as a datetime or similar datatype. If not, then you can cast them as such according to the above documentation.

Feel free to combine functions, as in:

select convert(varchar(10), nullif(MyColumn, '19000101'), 110) from MyTable;

OTHER TIPS

Try

declare @date varchar(10)
set @date = CONVERT(varchar(10),@startdate,110)
SELECT CASE WHEN  StartDate = '1900-01-01 00:00:00.000' THEN NULL
         ELSE CONVERT(VARCHAR(10), StartDate , 110)
       END AS StartDate 

FROM Table_Name

If you are looking to show the time with the date format requested try:

SELECT CONVERT(VARCHAR(10), GETDATE(), 110) + substring(CONVERT(VARCHAR(23), GETDATE(), 121),12,12)

For a comparative listing of the different formats for dates with the CONVERT command, use the code at http://rossql.blogspot.com/2014/04/sql-format-of-date-and-time-way-i-like.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top