Home >Database >Mysql Tutorial >How to Convert VARCHAR to DATETIME in SQL Server?

How to Convert VARCHAR to DATETIME in SQL Server?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-05 07:53:47957browse

How to Convert VARCHAR to DATETIME in SQL Server?

Converting VARCHAR to DATETIME in SQL Server

In SQL Server, you may encounter situations where you need to convert data from a VARCHAR (string) format to a DATETIME format. This conversion is necessary when you want to perform date-related operations or ensure the correct representation of temporal data.

To convert a VARCHAR to DATETIME, you can use the CONVERT() function. Here's how:

1. Convert to DATETIME:

To simply convert a VARCHAR value to a DATETIME, use the following syntax:

SELECT CONVERT(DATETIME, '2011-09-28 18:01:00', 120);

This will convert the string '2011-09-28 18:01:00' to a DATETIME object.

2. Convert to a Specific Format:

If you need to convert the DATETIME object to a specific format (e.g., '28-09-2011 18:01:00'), you can combine multiple CONVERT() functions to achieve the desired output:

SELECT
    CONVERT(VARCHAR(30), @date, 105) -- Italian format [28-09-2011 18:01:00]
    + ' ' +
    SELECT CONVERT(VARCHAR(30), @date, 108); -- Full date [with time/minutes/sec]

In this example, @date represents the DATETIME object you want to format.

The above is the detailed content of How to Convert VARCHAR to DATETIME in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn