Skip to content
Advertisement

How to extract date from a long string in SQL Server

I a long string like below in my column and I need to extract only the date (2021-07-05) from it.

Could anyone please help?

Name - Koteswararao vp Department - Prod Location - Hyderabad Domain - ND Job Title - Technical-ABAP Date of Hire - 2021-07-05 Vendor ID - v2345 Candidate ID - Associate ID - 3334 Name - Hardware Allocation

Advertisement

Answer

We can use PATINDEX with SUBSTRING here:

SELECT
    col,
    SUBSTRING(col,
              PATINDEX('%[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%', col),
              10) AS date
FROM yourTable;

Demo

The call to PATINDEX above finds the starting position of the date, while SUBSTRING takes 10 characters from that position.

Advertisement