Click here to Skip to main content
16,010,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have got a existing project that have database field nvarchar but it should be date time data type.Now I want to convert it date time but without touch of front int side code.I have a large number of data in data base.I have tested another place,when I change data type I have missed all of my data.I am in a deep fix.
How can I handle this matter.How can i change database Field Type without loosing data.
I am a novice developer,so
Any help will make me grateful
Masud
Posted
Updated 16-Jun-10 23:44pm
v2

1 solution

You need to change your nvarchar data into datetime by using below line of code. It's only example how can you change your nvarchar to datetime.


SQL
DECLARE @strFirstDate   varchar(20),
    @strSecondDate  varchar(20)
SELECT  @strFirstDate   = '20060120112128',
    @strSecondDate  = '20060120112659'
SELECT  CONVERT(datetime, LEFT(@strFirstDate, 8) + ' ' + substring(@strFirstDate, 9, 2) + ':' + substring(@strFirstDate, 11, 2) + ':' + substring(@strFirstDate, 13, 2)),
    CONVERT(datetime, LEFT(@strSecondDate, 8) + ' ' + substring(@strSecondDate, 9, 2) + ':' + substring(@strSecondDate, 11, 2) + ':' + substring(@strSecondDate, 13, 2)),
    DATEDIFF(Minute,    -- Or Hours / Seconds / whatever
        CONVERT(datetime, LEFT(@strFirstDate, 8) + ' ' + substring(@strFirstDate, 9, 2) + ':' + substring(@strFirstDate, 11, 2) + ':' + substring(@strFirstDate, 13, 2)),
        CONVERT(datetime, LEFT(@strSecondDate, 8) + ' ' + substring(@strSecondDate, 9, 2) + ':' + substring(@strSecondDate, 11, 2) + ':' + substring(@strSecondDate, 13, 2))
        )


I hope it works for you.
 
Share this answer
 
Comments
Mahmudunnabi 17-Jun-10 5:20am    
is it in sqlserver databased code
shukla dhaval 17-Jun-10 5:27am    
Yes it's sql server.
Mahmudunnabi 17-Jun-10 5:45am    
Yes,i got it but i need to change database field type without loosing data.Is their any way to it.
shukla dhaval 17-Jun-10 5:54am    
You don't need to change database field type at all. You just need to convert your nvarchar data into datetime format.

For Example. Select BirthDate from Table1 returns '20091002'
Now when you want to convert that nvarchar result into datetime then you need to change it like

Select Convert(datetime,left(birthdate,8)) from table1 it gives you result like 2009-10-02 (2nd -Oct -2009)

I hope it solve your issue.
Mahmudunnabi 17-Jun-10 6:11am    
thanks a lot

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900