SQL - Convert varchar to date

Tim Mullady 221 Reputation points
2021-02-11T18:16:36.923+00:00

Hello,

I have table with a date column in varchar data type. Some of the data has leading zero's and other do not. I've been struggling to adjust the data with CAST or Convert.

example:
07/13/2020
7/13/2020

I wanted to see if someone could help me adjust it to date type M/DD/YYYY

Thanks,

Tim

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,463 questions
{count} votes

2 additional answers

Sort by: Most helpful
  1. Guoxiong 8,126 Reputation points
    2021-02-11T18:55:40.207+00:00
    DECLARE @t TABLE (
     [Date] varchar(20)
    );
    INSERT INTO @t VALUES
    ('07/13/2020'), ('7/13/2020'), ('7/01/2020');
    
    -- Output format 7/1/2020
    SELECT REPLACE(CASE WHEN LEFT([Date], 1) = '0' THEN SUBSTRING([Date], 2, LEN([Date]) - 1) ELSE [Date] END, '/0', '/')
    FROM @t;
    
    --Output format 07/01/2020
    SELECT CONVERT(varchar(10), CAST([Date] AS date), 101)
    FROM @t;
    
    0 comments No comments

  2. Tom Phillips 17,691 Reputation points
    2021-02-11T19:00:45.7+00:00

    If you are using SQL 2016+

    DECLARE @t TABLE (
         [Date] varchar(20)
     );
     INSERT INTO @t VALUES
     ('07/13/2020'), ('7/13/2020'), ('7/01/2020');
    
    
     SELECT FORMAT(TRY_CAST([Date] as date),'M/d/yyyy')
     FROM @t
    
    0 comments No comments