Saturday, March 29, 2008

SQL Server 2005 Cast-Convert Date Time Format

Using CAST function in SQL Server 2005:


CAST (expression as datatype)

CAST function accepts expression name as column name or any SQL function that return expression or value and declare the datatype of the expression into which you want to cast/convert it.

Following are the SQL Server 2005 query syntax to cast DateTime into varchar:


USE Pubs

select cast(pubdate as varchar) from titles


select cast(getdate() as varchar)

Following are the MS SQL Server 2005 query Syntax to convert Time format:

SQL query to convert Time format into hh:mm:ss:

select convert(varchar, getdate(), 108)

SQL query to convert Time format into hh:mi:ss:mmm(24h):

select convert(varchar, getdate(), 114)

You can use datetime type column name instead of getdate() function.



select convert(varchar,pubdate,108) from titles


select convert(varchar,pubdate,114) from titles

No comments: