How to select a variable length string from between two known strings in SQL Server in a VARCHAR(MAX) where some columns don't have applicable strings










0















Using SQL Server 2012, I need to get from this example



ColumnName 
--------------------------------
Enroll to: Carol Goals are many and varied
characters that don't include desired results
Enroll to: Jan Levinson Goals will be discussed at first encounter
Enroll to: Stephon-Anderson Goals none
NULL
Enroll to: David Goals --Note uneven spaces, Need David


to extract the column to look like:



Name 
-----------
Carol
NULL
Jan Levinson
Stephon-Anderson
NULL
David


This code got me pretty close to the results I was looking for, but sometimes trimmed the name incorrectly.



Select 
CASE WHEN AssignedTo like '%Enroll To:%' THEN SUBSTRING(AssignedTo, CHARINDEX('%Enroll To:%', AssignedTo) + LEN('%Enroll To:%')
,CHARINDEX('Goals', AssignedTo) - CHARINDEX('%Enroll To:%', AssignedTo) + LEN('Goals'))
ELSE 'None'
END AS 'Name'
FROM
(

Select
CASE WHEN ColumnName like '%Enroll To:%' THEN SUBSTRING (ColumnName, CHARINDEX('Enroll To:', ColumnName), 40)


ELSE 'None'
END AS 'AssignedTo'

FROM TABLE ) A


I cannot thank you enough!










share|improve this question
























  • Please edit your question and provide real sample data. We can't guess at the answer.

    – Tim Biegeleisen
    Nov 5 '18 at 21:14











  • Real sample data provided. Thank you so much!

    – inefficientmkts
    Nov 7 '18 at 16:18















0















Using SQL Server 2012, I need to get from this example



ColumnName 
--------------------------------
Enroll to: Carol Goals are many and varied
characters that don't include desired results
Enroll to: Jan Levinson Goals will be discussed at first encounter
Enroll to: Stephon-Anderson Goals none
NULL
Enroll to: David Goals --Note uneven spaces, Need David


to extract the column to look like:



Name 
-----------
Carol
NULL
Jan Levinson
Stephon-Anderson
NULL
David


This code got me pretty close to the results I was looking for, but sometimes trimmed the name incorrectly.



Select 
CASE WHEN AssignedTo like '%Enroll To:%' THEN SUBSTRING(AssignedTo, CHARINDEX('%Enroll To:%', AssignedTo) + LEN('%Enroll To:%')
,CHARINDEX('Goals', AssignedTo) - CHARINDEX('%Enroll To:%', AssignedTo) + LEN('Goals'))
ELSE 'None'
END AS 'Name'
FROM
(

Select
CASE WHEN ColumnName like '%Enroll To:%' THEN SUBSTRING (ColumnName, CHARINDEX('Enroll To:', ColumnName), 40)


ELSE 'None'
END AS 'AssignedTo'

FROM TABLE ) A


I cannot thank you enough!










share|improve this question
























  • Please edit your question and provide real sample data. We can't guess at the answer.

    – Tim Biegeleisen
    Nov 5 '18 at 21:14











  • Real sample data provided. Thank you so much!

    – inefficientmkts
    Nov 7 '18 at 16:18













0












0








0








Using SQL Server 2012, I need to get from this example



ColumnName 
--------------------------------
Enroll to: Carol Goals are many and varied
characters that don't include desired results
Enroll to: Jan Levinson Goals will be discussed at first encounter
Enroll to: Stephon-Anderson Goals none
NULL
Enroll to: David Goals --Note uneven spaces, Need David


to extract the column to look like:



Name 
-----------
Carol
NULL
Jan Levinson
Stephon-Anderson
NULL
David


This code got me pretty close to the results I was looking for, but sometimes trimmed the name incorrectly.



Select 
CASE WHEN AssignedTo like '%Enroll To:%' THEN SUBSTRING(AssignedTo, CHARINDEX('%Enroll To:%', AssignedTo) + LEN('%Enroll To:%')
,CHARINDEX('Goals', AssignedTo) - CHARINDEX('%Enroll To:%', AssignedTo) + LEN('Goals'))
ELSE 'None'
END AS 'Name'
FROM
(

Select
CASE WHEN ColumnName like '%Enroll To:%' THEN SUBSTRING (ColumnName, CHARINDEX('Enroll To:', ColumnName), 40)


ELSE 'None'
END AS 'AssignedTo'

FROM TABLE ) A


I cannot thank you enough!










share|improve this question
















Using SQL Server 2012, I need to get from this example



ColumnName 
--------------------------------
Enroll to: Carol Goals are many and varied
characters that don't include desired results
Enroll to: Jan Levinson Goals will be discussed at first encounter
Enroll to: Stephon-Anderson Goals none
NULL
Enroll to: David Goals --Note uneven spaces, Need David


to extract the column to look like:



Name 
-----------
Carol
NULL
Jan Levinson
Stephon-Anderson
NULL
David


This code got me pretty close to the results I was looking for, but sometimes trimmed the name incorrectly.



Select 
CASE WHEN AssignedTo like '%Enroll To:%' THEN SUBSTRING(AssignedTo, CHARINDEX('%Enroll To:%', AssignedTo) + LEN('%Enroll To:%')
,CHARINDEX('Goals', AssignedTo) - CHARINDEX('%Enroll To:%', AssignedTo) + LEN('Goals'))
ELSE 'None'
END AS 'Name'
FROM
(

Select
CASE WHEN ColumnName like '%Enroll To:%' THEN SUBSTRING (ColumnName, CHARINDEX('Enroll To:', ColumnName), 40)


ELSE 'None'
END AS 'AssignedTo'

FROM TABLE ) A


I cannot thank you enough!







sql-server tsql varcharmax






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 19:22







inefficientmkts

















asked Nov 5 '18 at 20:25









inefficientmktsinefficientmkts

295




295












  • Please edit your question and provide real sample data. We can't guess at the answer.

    – Tim Biegeleisen
    Nov 5 '18 at 21:14











  • Real sample data provided. Thank you so much!

    – inefficientmkts
    Nov 7 '18 at 16:18

















  • Please edit your question and provide real sample data. We can't guess at the answer.

    – Tim Biegeleisen
    Nov 5 '18 at 21:14











  • Real sample data provided. Thank you so much!

    – inefficientmkts
    Nov 7 '18 at 16:18
















Please edit your question and provide real sample data. We can't guess at the answer.

– Tim Biegeleisen
Nov 5 '18 at 21:14





Please edit your question and provide real sample data. We can't guess at the answer.

– Tim Biegeleisen
Nov 5 '18 at 21:14













Real sample data provided. Thank you so much!

– inefficientmkts
Nov 7 '18 at 16:18





Real sample data provided. Thank you so much!

– inefficientmkts
Nov 7 '18 at 16:18












4 Answers
4






active

oldest

votes


















0














You can use apply and string functions:



select left(v.s1, charindex(' ', s1) - 1)
from t cross apply
(values (stuff(t.col, 1, 11, '')) v(s1)





share|improve this answer























  • Should clarify that there are a variable number of characters before and after the fields in 'columnname'

    – inefficientmkts
    Nov 5 '18 at 20:51


















0














Here is an alternative to Gordon's answer:



SELECT
SUBSTRING(ColumnName,
CHARINDEX(':', ColumnName) + 2,
CHARINDEX(' ', ColumnName, CHARINDEX(':', ColumnName) + 2) -
CHARINDEX(':', ColumnName) - 2) AS Name
FROM yourTable;



Demo






share|improve this answer

























  • There's a variable length of data before and after the field information shown

    – inefficientmkts
    Nov 5 '18 at 20:44











  • @inefficientmkts Answer updated. It works now with a variable field width.

    – Tim Biegeleisen
    Nov 5 '18 at 20:54












  • Thank you very much. I tried it and the same error is produced "invalid length parameter passed to the left or substring function' There may be other instances in the field where a : or ' ' exists. Dunno if that helps

    – inefficientmkts
    Nov 5 '18 at 21:08











  • @inefficientmkts Your sample data is working in this demo. I am asking you for data which exposes the problems in my answer, and you still have not provided that. I can't help you without seeing your data.

    – Tim Biegeleisen
    Nov 5 '18 at 21:11











  • My apologies Tim- I didn't recognize and properly identify some of the variations within the column. I have provided the working data you requested. Thanks again, this really has me stumped.

    – inefficientmkts
    Nov 7 '18 at 16:34


















0














This produced the desired result and seems to deal with variable length of the target string. Hope it helps someone.



DECLARE @pretext as NVARCHAR(100) = 'Enroll to:' 
DECLARE @posttext as NVARCHAR(100) = 'Goals'

Select
,CASE When CHARINDEX(@posttext, ColumnName) - (CHARINDEX(@pretext, ColumnName) + len(@pretext)) < 0 THEN NULL
Else
SUBSTRING(ColumnName, CHARINDEX(@pretext, ColumnName) + len(@pretext)
,CHARINDEX(@posttext, ColumnName) - (CHARINDEX(@pretext, ColumnName) + len(@pretext)) )
END as betweentext

FROM TABLE





share|improve this answer
































    0














    Here is your data to test for in table form:



    declare @goals table (string nvarchar(255));
    insert @goals values
    ('Enroll to: Carol Goals are many and varied characters that don''t include desired results'),
    ('Enroll to: Jan Levinson Goals will be discussed at first encounter'),
    ('Enroll to: Stephon-Anderson Goals none'),
    (NULL),
    ('Enroll to: David Goals '), --Note uneven spaces, Need David
    (' '); -- I (psw) added this


    And the following code seems to do what you desire without error. But it is assuming that your sentence after the name will always start with "Goals".



    select *,
    result =
    case
    when isValid = 1 then
    ltrim(rtrim(
    substring(string, colonPos + 1, goalsPos - colonPos - 1)
    ))
    end

    from @goals
    cross apply (select
    colonPos = charindex(':', string),
    goalsPos = patIndex('%goals%', string)
    ) positions
    cross apply (select
    isValid =
    case
    when colonPos = 0 or goalsPos = 0 or colonPos > goalsPos then 0
    else 1
    end
    ) validity





    share|improve this answer






















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53161695%2fhow-to-select-a-variable-length-string-from-between-two-known-strings-in-sql-ser%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      You can use apply and string functions:



      select left(v.s1, charindex(' ', s1) - 1)
      from t cross apply
      (values (stuff(t.col, 1, 11, '')) v(s1)





      share|improve this answer























      • Should clarify that there are a variable number of characters before and after the fields in 'columnname'

        – inefficientmkts
        Nov 5 '18 at 20:51















      0














      You can use apply and string functions:



      select left(v.s1, charindex(' ', s1) - 1)
      from t cross apply
      (values (stuff(t.col, 1, 11, '')) v(s1)





      share|improve this answer























      • Should clarify that there are a variable number of characters before and after the fields in 'columnname'

        – inefficientmkts
        Nov 5 '18 at 20:51













      0












      0








      0







      You can use apply and string functions:



      select left(v.s1, charindex(' ', s1) - 1)
      from t cross apply
      (values (stuff(t.col, 1, 11, '')) v(s1)





      share|improve this answer













      You can use apply and string functions:



      select left(v.s1, charindex(' ', s1) - 1)
      from t cross apply
      (values (stuff(t.col, 1, 11, '')) v(s1)






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 5 '18 at 20:27









      Gordon LinoffGordon Linoff

      764k35296400




      764k35296400












      • Should clarify that there are a variable number of characters before and after the fields in 'columnname'

        – inefficientmkts
        Nov 5 '18 at 20:51

















      • Should clarify that there are a variable number of characters before and after the fields in 'columnname'

        – inefficientmkts
        Nov 5 '18 at 20:51
















      Should clarify that there are a variable number of characters before and after the fields in 'columnname'

      – inefficientmkts
      Nov 5 '18 at 20:51





      Should clarify that there are a variable number of characters before and after the fields in 'columnname'

      – inefficientmkts
      Nov 5 '18 at 20:51













      0














      Here is an alternative to Gordon's answer:



      SELECT
      SUBSTRING(ColumnName,
      CHARINDEX(':', ColumnName) + 2,
      CHARINDEX(' ', ColumnName, CHARINDEX(':', ColumnName) + 2) -
      CHARINDEX(':', ColumnName) - 2) AS Name
      FROM yourTable;



      Demo






      share|improve this answer

























      • There's a variable length of data before and after the field information shown

        – inefficientmkts
        Nov 5 '18 at 20:44











      • @inefficientmkts Answer updated. It works now with a variable field width.

        – Tim Biegeleisen
        Nov 5 '18 at 20:54












      • Thank you very much. I tried it and the same error is produced "invalid length parameter passed to the left or substring function' There may be other instances in the field where a : or ' ' exists. Dunno if that helps

        – inefficientmkts
        Nov 5 '18 at 21:08











      • @inefficientmkts Your sample data is working in this demo. I am asking you for data which exposes the problems in my answer, and you still have not provided that. I can't help you without seeing your data.

        – Tim Biegeleisen
        Nov 5 '18 at 21:11











      • My apologies Tim- I didn't recognize and properly identify some of the variations within the column. I have provided the working data you requested. Thanks again, this really has me stumped.

        – inefficientmkts
        Nov 7 '18 at 16:34















      0














      Here is an alternative to Gordon's answer:



      SELECT
      SUBSTRING(ColumnName,
      CHARINDEX(':', ColumnName) + 2,
      CHARINDEX(' ', ColumnName, CHARINDEX(':', ColumnName) + 2) -
      CHARINDEX(':', ColumnName) - 2) AS Name
      FROM yourTable;



      Demo






      share|improve this answer

























      • There's a variable length of data before and after the field information shown

        – inefficientmkts
        Nov 5 '18 at 20:44











      • @inefficientmkts Answer updated. It works now with a variable field width.

        – Tim Biegeleisen
        Nov 5 '18 at 20:54












      • Thank you very much. I tried it and the same error is produced "invalid length parameter passed to the left or substring function' There may be other instances in the field where a : or ' ' exists. Dunno if that helps

        – inefficientmkts
        Nov 5 '18 at 21:08











      • @inefficientmkts Your sample data is working in this demo. I am asking you for data which exposes the problems in my answer, and you still have not provided that. I can't help you without seeing your data.

        – Tim Biegeleisen
        Nov 5 '18 at 21:11











      • My apologies Tim- I didn't recognize and properly identify some of the variations within the column. I have provided the working data you requested. Thanks again, this really has me stumped.

        – inefficientmkts
        Nov 7 '18 at 16:34













      0












      0








      0







      Here is an alternative to Gordon's answer:



      SELECT
      SUBSTRING(ColumnName,
      CHARINDEX(':', ColumnName) + 2,
      CHARINDEX(' ', ColumnName, CHARINDEX(':', ColumnName) + 2) -
      CHARINDEX(':', ColumnName) - 2) AS Name
      FROM yourTable;



      Demo






      share|improve this answer















      Here is an alternative to Gordon's answer:



      SELECT
      SUBSTRING(ColumnName,
      CHARINDEX(':', ColumnName) + 2,
      CHARINDEX(' ', ColumnName, CHARINDEX(':', ColumnName) + 2) -
      CHARINDEX(':', ColumnName) - 2) AS Name
      FROM yourTable;



      Demo







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 5 '18 at 20:54

























      answered Nov 5 '18 at 20:34









      Tim BiegeleisenTim Biegeleisen

      221k1388141




      221k1388141












      • There's a variable length of data before and after the field information shown

        – inefficientmkts
        Nov 5 '18 at 20:44











      • @inefficientmkts Answer updated. It works now with a variable field width.

        – Tim Biegeleisen
        Nov 5 '18 at 20:54












      • Thank you very much. I tried it and the same error is produced "invalid length parameter passed to the left or substring function' There may be other instances in the field where a : or ' ' exists. Dunno if that helps

        – inefficientmkts
        Nov 5 '18 at 21:08











      • @inefficientmkts Your sample data is working in this demo. I am asking you for data which exposes the problems in my answer, and you still have not provided that. I can't help you without seeing your data.

        – Tim Biegeleisen
        Nov 5 '18 at 21:11











      • My apologies Tim- I didn't recognize and properly identify some of the variations within the column. I have provided the working data you requested. Thanks again, this really has me stumped.

        – inefficientmkts
        Nov 7 '18 at 16:34

















      • There's a variable length of data before and after the field information shown

        – inefficientmkts
        Nov 5 '18 at 20:44











      • @inefficientmkts Answer updated. It works now with a variable field width.

        – Tim Biegeleisen
        Nov 5 '18 at 20:54












      • Thank you very much. I tried it and the same error is produced "invalid length parameter passed to the left or substring function' There may be other instances in the field where a : or ' ' exists. Dunno if that helps

        – inefficientmkts
        Nov 5 '18 at 21:08











      • @inefficientmkts Your sample data is working in this demo. I am asking you for data which exposes the problems in my answer, and you still have not provided that. I can't help you without seeing your data.

        – Tim Biegeleisen
        Nov 5 '18 at 21:11











      • My apologies Tim- I didn't recognize and properly identify some of the variations within the column. I have provided the working data you requested. Thanks again, this really has me stumped.

        – inefficientmkts
        Nov 7 '18 at 16:34
















      There's a variable length of data before and after the field information shown

      – inefficientmkts
      Nov 5 '18 at 20:44





      There's a variable length of data before and after the field information shown

      – inefficientmkts
      Nov 5 '18 at 20:44













      @inefficientmkts Answer updated. It works now with a variable field width.

      – Tim Biegeleisen
      Nov 5 '18 at 20:54






      @inefficientmkts Answer updated. It works now with a variable field width.

      – Tim Biegeleisen
      Nov 5 '18 at 20:54














      Thank you very much. I tried it and the same error is produced "invalid length parameter passed to the left or substring function' There may be other instances in the field where a : or ' ' exists. Dunno if that helps

      – inefficientmkts
      Nov 5 '18 at 21:08





      Thank you very much. I tried it and the same error is produced "invalid length parameter passed to the left or substring function' There may be other instances in the field where a : or ' ' exists. Dunno if that helps

      – inefficientmkts
      Nov 5 '18 at 21:08













      @inefficientmkts Your sample data is working in this demo. I am asking you for data which exposes the problems in my answer, and you still have not provided that. I can't help you without seeing your data.

      – Tim Biegeleisen
      Nov 5 '18 at 21:11





      @inefficientmkts Your sample data is working in this demo. I am asking you for data which exposes the problems in my answer, and you still have not provided that. I can't help you without seeing your data.

      – Tim Biegeleisen
      Nov 5 '18 at 21:11













      My apologies Tim- I didn't recognize and properly identify some of the variations within the column. I have provided the working data you requested. Thanks again, this really has me stumped.

      – inefficientmkts
      Nov 7 '18 at 16:34





      My apologies Tim- I didn't recognize and properly identify some of the variations within the column. I have provided the working data you requested. Thanks again, this really has me stumped.

      – inefficientmkts
      Nov 7 '18 at 16:34











      0














      This produced the desired result and seems to deal with variable length of the target string. Hope it helps someone.



      DECLARE @pretext as NVARCHAR(100) = 'Enroll to:' 
      DECLARE @posttext as NVARCHAR(100) = 'Goals'

      Select
      ,CASE When CHARINDEX(@posttext, ColumnName) - (CHARINDEX(@pretext, ColumnName) + len(@pretext)) < 0 THEN NULL
      Else
      SUBSTRING(ColumnName, CHARINDEX(@pretext, ColumnName) + len(@pretext)
      ,CHARINDEX(@posttext, ColumnName) - (CHARINDEX(@pretext, ColumnName) + len(@pretext)) )
      END as betweentext

      FROM TABLE





      share|improve this answer





























        0














        This produced the desired result and seems to deal with variable length of the target string. Hope it helps someone.



        DECLARE @pretext as NVARCHAR(100) = 'Enroll to:' 
        DECLARE @posttext as NVARCHAR(100) = 'Goals'

        Select
        ,CASE When CHARINDEX(@posttext, ColumnName) - (CHARINDEX(@pretext, ColumnName) + len(@pretext)) < 0 THEN NULL
        Else
        SUBSTRING(ColumnName, CHARINDEX(@pretext, ColumnName) + len(@pretext)
        ,CHARINDEX(@posttext, ColumnName) - (CHARINDEX(@pretext, ColumnName) + len(@pretext)) )
        END as betweentext

        FROM TABLE





        share|improve this answer



























          0












          0








          0







          This produced the desired result and seems to deal with variable length of the target string. Hope it helps someone.



          DECLARE @pretext as NVARCHAR(100) = 'Enroll to:' 
          DECLARE @posttext as NVARCHAR(100) = 'Goals'

          Select
          ,CASE When CHARINDEX(@posttext, ColumnName) - (CHARINDEX(@pretext, ColumnName) + len(@pretext)) < 0 THEN NULL
          Else
          SUBSTRING(ColumnName, CHARINDEX(@pretext, ColumnName) + len(@pretext)
          ,CHARINDEX(@posttext, ColumnName) - (CHARINDEX(@pretext, ColumnName) + len(@pretext)) )
          END as betweentext

          FROM TABLE





          share|improve this answer















          This produced the desired result and seems to deal with variable length of the target string. Hope it helps someone.



          DECLARE @pretext as NVARCHAR(100) = 'Enroll to:' 
          DECLARE @posttext as NVARCHAR(100) = 'Goals'

          Select
          ,CASE When CHARINDEX(@posttext, ColumnName) - (CHARINDEX(@pretext, ColumnName) + len(@pretext)) < 0 THEN NULL
          Else
          SUBSTRING(ColumnName, CHARINDEX(@pretext, ColumnName) + len(@pretext)
          ,CHARINDEX(@posttext, ColumnName) - (CHARINDEX(@pretext, ColumnName) + len(@pretext)) )
          END as betweentext

          FROM TABLE






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 7 '18 at 19:52

























          answered Nov 5 '18 at 22:08









          inefficientmktsinefficientmkts

          295




          295





















              0














              Here is your data to test for in table form:



              declare @goals table (string nvarchar(255));
              insert @goals values
              ('Enroll to: Carol Goals are many and varied characters that don''t include desired results'),
              ('Enroll to: Jan Levinson Goals will be discussed at first encounter'),
              ('Enroll to: Stephon-Anderson Goals none'),
              (NULL),
              ('Enroll to: David Goals '), --Note uneven spaces, Need David
              (' '); -- I (psw) added this


              And the following code seems to do what you desire without error. But it is assuming that your sentence after the name will always start with "Goals".



              select *,
              result =
              case
              when isValid = 1 then
              ltrim(rtrim(
              substring(string, colonPos + 1, goalsPos - colonPos - 1)
              ))
              end

              from @goals
              cross apply (select
              colonPos = charindex(':', string),
              goalsPos = patIndex('%goals%', string)
              ) positions
              cross apply (select
              isValid =
              case
              when colonPos = 0 or goalsPos = 0 or colonPos > goalsPos then 0
              else 1
              end
              ) validity





              share|improve this answer



























                0














                Here is your data to test for in table form:



                declare @goals table (string nvarchar(255));
                insert @goals values
                ('Enroll to: Carol Goals are many and varied characters that don''t include desired results'),
                ('Enroll to: Jan Levinson Goals will be discussed at first encounter'),
                ('Enroll to: Stephon-Anderson Goals none'),
                (NULL),
                ('Enroll to: David Goals '), --Note uneven spaces, Need David
                (' '); -- I (psw) added this


                And the following code seems to do what you desire without error. But it is assuming that your sentence after the name will always start with "Goals".



                select *,
                result =
                case
                when isValid = 1 then
                ltrim(rtrim(
                substring(string, colonPos + 1, goalsPos - colonPos - 1)
                ))
                end

                from @goals
                cross apply (select
                colonPos = charindex(':', string),
                goalsPos = patIndex('%goals%', string)
                ) positions
                cross apply (select
                isValid =
                case
                when colonPos = 0 or goalsPos = 0 or colonPos > goalsPos then 0
                else 1
                end
                ) validity





                share|improve this answer

























                  0












                  0








                  0







                  Here is your data to test for in table form:



                  declare @goals table (string nvarchar(255));
                  insert @goals values
                  ('Enroll to: Carol Goals are many and varied characters that don''t include desired results'),
                  ('Enroll to: Jan Levinson Goals will be discussed at first encounter'),
                  ('Enroll to: Stephon-Anderson Goals none'),
                  (NULL),
                  ('Enroll to: David Goals '), --Note uneven spaces, Need David
                  (' '); -- I (psw) added this


                  And the following code seems to do what you desire without error. But it is assuming that your sentence after the name will always start with "Goals".



                  select *,
                  result =
                  case
                  when isValid = 1 then
                  ltrim(rtrim(
                  substring(string, colonPos + 1, goalsPos - colonPos - 1)
                  ))
                  end

                  from @goals
                  cross apply (select
                  colonPos = charindex(':', string),
                  goalsPos = patIndex('%goals%', string)
                  ) positions
                  cross apply (select
                  isValid =
                  case
                  when colonPos = 0 or goalsPos = 0 or colonPos > goalsPos then 0
                  else 1
                  end
                  ) validity





                  share|improve this answer













                  Here is your data to test for in table form:



                  declare @goals table (string nvarchar(255));
                  insert @goals values
                  ('Enroll to: Carol Goals are many and varied characters that don''t include desired results'),
                  ('Enroll to: Jan Levinson Goals will be discussed at first encounter'),
                  ('Enroll to: Stephon-Anderson Goals none'),
                  (NULL),
                  ('Enroll to: David Goals '), --Note uneven spaces, Need David
                  (' '); -- I (psw) added this


                  And the following code seems to do what you desire without error. But it is assuming that your sentence after the name will always start with "Goals".



                  select *,
                  result =
                  case
                  when isValid = 1 then
                  ltrim(rtrim(
                  substring(string, colonPos + 1, goalsPos - colonPos - 1)
                  ))
                  end

                  from @goals
                  cross apply (select
                  colonPos = charindex(':', string),
                  goalsPos = patIndex('%goals%', string)
                  ) positions
                  cross apply (select
                  isValid =
                  case
                  when colonPos = 0 or goalsPos = 0 or colonPos > goalsPos then 0
                  else 1
                  end
                  ) validity






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 7 '18 at 20:12









                  pwilcoxpwilcox

                  540213




                  540213



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53161695%2fhow-to-select-a-variable-length-string-from-between-two-known-strings-in-sql-ser%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Top Tejano songwriter Luis Silva dead of heart attack at 64

                      ReactJS Fetched API data displays live - need Data displayed static

                      政党