SQL: extract date from string

There is a text field myDate. This field can contain either 1) "Fiscal year ending with someDate", or 2) "dateA to" dateB.

In situation 1), I want to set the field date1 = someDate.

In situation 2), I want to set the field date1 = dateA and the field date2 = dateB.

All dates (someDate, dateA, dateB) can be written as 1/1/2000, January 1, 2000 or January 1, 2000.

How can I extract dates from myDate and paste them into the correct fields?

+3
source share
1 answer

, "" . DATETIME- SQL - , , :

SELECT CAST('1/1/2000' AS DATETIME), CAST('January 1, 2000' AS DATETIME), CAST('Jan 1, 2000' AS DATETIME)

-1 +1 , DATEADD, .

SELECT DATEADD(dd, 1, DATEADD(yy, -1, 'January 1 2000'))

... , , . , - :

SELECT
  CASE 
    WHEN myDate LIKE 'fiscal year ending %' THEN CAST(DATEADD(dd, 1, DATEADD(yy, -1, REPLACE(myDate, 'fiscal year ending ', ''))) AS DATETIME) 
    ELSE CAST(LEFT(myDate, PATINDEX('% to %', myDate)) AS DATETIME)
  END 'FromDate',
  CASE
    WHEN myDate LIKE 'fiscal year ending %' THEN CAST(REPLACE(myDate, 'fiscal year ending ', '') AS DATETIME)
    ELSE CAST(SUBSTRING(myDate, PATINDEX('% to %', myDate) + 4, 100) AS DATETIME)
  END 'ToDate'
FROM 
  ...whatever

... . , , , , , .

, , , / . , 1/1/2000 1 , 3/4/2000 ?

+5

Source: https://habr.com/ru/post/1753173/


All Articles