Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Varchar into Time in SQL Server

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.

like image 253
SarangArd Avatar asked Apr 18 '13 05:04

SarangArd


People also ask

How do I convert text to date in SQL?

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.

How can convert date and time in SQL Server?

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.


2 Answers

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.

like image 105
Alpesh Gediya Avatar answered Oct 23 '22 01:10

Alpesh Gediya


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.

like image 20
RichardTheKiwi Avatar answered Oct 23 '22 00:10

RichardTheKiwi