简体   繁体   中英

How to extract only date from string in SQL Server

I want to extract only date from below string and extract year alone from this date.

String:

'I was born on 1st Jan 1994'

Do we have any function to extract dates from strings other than left or right functions ?

SELECT RIGHT('I was born on 1st Jan 1994', 12) 

Result: '1st Jan 1994'

But I need result in date format.

Please check my code and resultset for your request: I mostly used another string functions other than left() and right(): I hope It solves your problem.

DECLARE @string VARCHAR(100)
DECLARE @extract VARCHAR(20)
DECLARE @onlydate VARCHAR(20)
SET @string = 'I was born on 1st Jan 1994'
SET @extract = SUBSTRING(@string, CHARINDEX('1st', @string), len(@string))
SET @onlydate = REPLACE(@extract, 'st', '')
SELECT @string as full_text, @extract as extracted_text, @onlydate as only_datetext,CONVERT(date,@onlydate,102) as string_to_date;

Result_Set查询结果字符串到日期

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM