How do i convert the Time format " 10:02:22 PM " into an SQL Server DateTime Format.
I have a column of such data. I imported this column from a CSV File and now want to convert it into a DateTime Format so that i can be able to use Date Time Functions.
I want to be able to insert this column into another table with correct DateTime format.
SQL Server: Convert string to date explicitly In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.
We can convert the Date into Datetime in two ways. Using CONVERT() function: Convert means to change the form or value of something. The CONVERT() function in the SQL server is used to convert a value of one type to another type. Convert() function is used to convert a value of any type to another datatype.
Use this link : http://msdn.microsoft.com/en-us/library/ms187928.aspx.
For only time conversion...
SELECT CONVERT( TIME, '10:00:22 PM' );
Gives the following output...
22:00:22.000000
Time conversion with date and time...
SELECT CONVERT( DATETIME, '10:00:22 PM' );
Gives the following output...
1900-01-01 22:00:22.0000
Note : For datetime
you need to have specific date as input otherwise it consider default century date.
You don't need to convert it. An implicit cast occurs when you use
INSERT otherTable
SELECT ....., timeAsVarchar, ...
FROM csvTable
If all the time data (leading space or not) is parseable from the string, the query will work beautifully. If however, there is the possibility of bad or blank data that cannot be converted to a time, test it first
INSERT otherTable
SELECT ....., CASE WHEN ISDATE(timeAsVarchar)=1 THEN timeAsVarchar END, ...
FROM csvTable
ELSE NULL
is implied so I left it out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With