extract of text from column and copy it into a new column

别来无恙 提交于 2019-12-25 11:10:19

问题


I want to extract text from a column and place it into a column of its own.

The Text is always 16 characters long in a DD/MM/YYYY HH:MM format, appears the text "On-site" which only ever appears once in the text and is always followed by the text "Off-Site" which also only appears once.

This is the code that I am using at the moment but I dont have it set right at all.

WITH
   LEFT(SUBSTRING(eventcomments,
                     CHARINDEX('On-Site', r.eventcomments) + 1, 16),
                     CHARINDEX('Off-Site', r.eventcomments) - 1) AS Onsite

I am getting this error message.

Invalid length parameter passed to the LEFT or SUBSTRING function.

回答1:


Assuming that I would have to extract from a string column first occurrence of a date/time values having following format DD/MM/YYYY HH:SS (length = 16 chars) then I would use PATINDEX instead of CHARINDEX thus:

SELECT  *, 
    SUBSTRING(
        x.StringColumn, 
        NULLIF(PATINDEX('%[0-1][0-9]/[0-3][0-9]/[0-9][0-9][0-9][0-9][ ][0-9][0-9]:[0-9][0-9]%', x.StringColumn), 0), 
        16) AS DateTimeExtracted
FROM    (VALUES 
    ('Bogdanel 01/02/2017 03:04 hei ho'),
    ('Georgel 05/06/2017 07:08 danga langa'),
    ('Suna''n asfintit 09/11/2018 11:22 hei talanga'),
    ('Danga langa. Pai da.'),
    ('   '),
    (NULL)
) x(StringColumn)

Results:

StringColumn                                 DateTimeExtracted
-------------------------------------------- -----------------
Bogdanel 01/02/2017 03:04 hei ho             01/02/2017 03:04
Georgel 05/06/2017 07:08 danga langa         05/06/2017 07:08
Suna'n asfintit 09/11/2018 11:22 hei talanga 09/11/2018 11:22
Danga langa. Pai da.                         NULL
                                             NULL
NULL                                         NULL



回答2:


This happens because the values are not in the field. A simple method just adds them in for the charindex():

  LEFT(SUBSTRING(eventcomments,
                 CHARINDEX('On-Site', r.eventcomments + 'On-Site') + 1, 16),
       CHARINDEX('Off-Site', r.eventcomments + 'Off-Site') - 1
      ) AS Onsite

You'll need to test the code to see if it does what you want. This approach will prevent the error.



来源:https://stackoverflow.com/questions/44885387/extract-of-text-from-column-and-copy-it-into-a-new-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!