How to Convert a Transact-SQL Date to a String

104 13

    Using Convert

    • 1). Determine which data you need to display in your query.

    • 2). Write a select statement using the convert function. Here is an example that takes the current date and converts it:

      SELECT

      CONVERT(varchar(30), GETDATE(), 0) AS ConvertDate;

      This example takes the default format "2011-08-01 13:16:58.527" and converts it to the "Aug 1 2011 1:16PM" format. When using the convert function, you must specify which date and time style you would like to use, which in this example is the default date and time style "100."

    • 3). Write a select statement to select data from a specific table:

      SELECT

      CONVERT(varchar(30), TableDateColumn, 0) AS ConvertDate

      FROM TableName;

    Using Cast

    • 1). Determine the data you need to display in your query.

    • 2). Write a select statement using the cast function. Here is an example that takes the current date and converts it:

      SELECT

      CAST(GETDATE() AS varchar(30)) AS CastDate;

      This example takes the default format "2011-08-01 13:16:58.527" and converts it to the "Aug 1 2011 1:16PM" format. With the cast function, you do not need to specify which style you want to use, as the function automatically uses the default style.

    • 3). Write a select statement to select data from a specific table:

      SELECT

      CAST(TableDateColumn AS varchar(30)) AS CastDate

      FROM TableName;

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.