How to insert string_split output in a table? The Next CEO of Stack OverflowAdd a column with a default value to an existing table in SQL ServerHow to check if a column exists in a SQL Server table?Table Naming Dilemma: Singular vs. Plural NamesInserting multiple rows in a single SQL query?Insert results of a stored procedure into a temporary tableHow do I UPDATE from a SELECT in SQL Server?SQL Custom selectionInserting records from another queryOracle SQL : Updating a column with SUM query of another tablemysql table linear structure

How to install OpenCV on Raspbian Stretch?

Proper way to express "He disappeared them"

Does soap repel water?

Is it convenient to ask the journal's editor for two additional days to complete a review?

Chain wire methods together in Lightning Web Components

Would a completely good Muggle be able to use a wand?

Is wanting to ask what to write an indication that you need to change your story?

Is micro rebar a better way to reinforce concrete than rebar?

Domestic-to-international connection at Orlando (MCO)

Bartok - Syncopation (1): Meaning of notes in between Grand Staff

Why isn't acceleration always zero whenever velocity is zero, such as the moment a ball bounces off a wall?

Why doesn't UK go for the same deal Japan has with EU to resolve Brexit?

Rotate a column

RigExpert AA-35 - Interpreting The Information

Newlines in BSD sed vs gsed

What steps are necessary to read a Modern SSD in Medieval Europe?

Can a Bladesinger Wizard use Bladesong with a Hand Crossbow?

Is it possible to use a NPN BJT as switch, from single power source?

Why did CATV standarize in 75 ohms and everyone else in 50?

What was the first Unix version to run on a microcomputer?

Is a distribution that is normal, but highly skewed considered Gaussian?

When you upcast Blindness/Deafness, do all targets suffer the same effect?

Writing differences on a blackboard

Why is quantifier elimination desirable for a given theory?



How to insert string_split output in a table?



The Next CEO of Stack OverflowAdd a column with a default value to an existing table in SQL ServerHow to check if a column exists in a SQL Server table?Table Naming Dilemma: Singular vs. Plural NamesInserting multiple rows in a single SQL query?Insert results of a stored procedure into a temporary tableHow do I UPDATE from a SELECT in SQL Server?SQL Custom selectionInserting records from another queryOracle SQL : Updating a column with SUM query of another tablemysql table linear structure










1















I have a string which I need to insert into a table after extracting values out of it. An example string is like this:



111111,1111,11.11,'2019-01-01-11.11.11.111111'#222222,2222,22.22,'2019-02-02-22.22.22.222222'


Using string_split, I can get split the values in different rows:



declare @s varchar(1000)
set @s = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222'''

select value from string_split(@s, '#')

--Output
--111111,1111,11.11,'2019-01-01-11.11.11.111111'
--222222,2222,22.22,'2019-02-02-22.22.22.222222'


It gets interesting.



The output needs to be inserted to a table. I have thought about dynamic SQL, but am not too fond of that:



declare @SQLstatment varchar(1000)
set @SQLstatment = 'insert into MyTable (Col1,Col2,Col3,Col4) values (' + OUTPUT_FROM_SPLIT + ')'
exec (@SQLstatment)


It gets more interesting.



Col4 is of DB2 data type timestamp. I need to convert it to SQL Server 2016 datetime2 data type using this statement I wrote:



declare @DB2_timpstamp varchar(30) = '2019-02-25-11.22.33.456789'
select convert(datetime2, stuff(stuff(stuff(@DB2_timpstamp, 17, 1, ':'), 14, 1, ':'), 11, 1, ' '))


Problem



I cannot make this all work.



I want to avoid using dynamic SQL as much as I can. Most probably I've to use loops. A solution will look like this:



while(SOME_CONDITION)
begin
insert into MyTable (Col1,Col2,Col3,Col4) values
(Val1,Val2,Val3,convert(datetime2, stuff(stuff(stuff(Val4, 17, 1, ':'), 14, 1, ':'), 11, 1, ' ')))
LOOP_VARIABLE_INCREMENT
end









share|improve this question






















  • You don't want or need dynamic sql or loops here. It seems you have data that has the rows delimited with '#' and columns delimited with a comma. You will need to split the values a second time to get columns. Why is the source data so hostile?

    – Sean Lange
    Mar 8 at 15:47















1















I have a string which I need to insert into a table after extracting values out of it. An example string is like this:



111111,1111,11.11,'2019-01-01-11.11.11.111111'#222222,2222,22.22,'2019-02-02-22.22.22.222222'


Using string_split, I can get split the values in different rows:



declare @s varchar(1000)
set @s = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222'''

select value from string_split(@s, '#')

--Output
--111111,1111,11.11,'2019-01-01-11.11.11.111111'
--222222,2222,22.22,'2019-02-02-22.22.22.222222'


It gets interesting.



The output needs to be inserted to a table. I have thought about dynamic SQL, but am not too fond of that:



declare @SQLstatment varchar(1000)
set @SQLstatment = 'insert into MyTable (Col1,Col2,Col3,Col4) values (' + OUTPUT_FROM_SPLIT + ')'
exec (@SQLstatment)


It gets more interesting.



Col4 is of DB2 data type timestamp. I need to convert it to SQL Server 2016 datetime2 data type using this statement I wrote:



declare @DB2_timpstamp varchar(30) = '2019-02-25-11.22.33.456789'
select convert(datetime2, stuff(stuff(stuff(@DB2_timpstamp, 17, 1, ':'), 14, 1, ':'), 11, 1, ' '))


Problem



I cannot make this all work.



I want to avoid using dynamic SQL as much as I can. Most probably I've to use loops. A solution will look like this:



while(SOME_CONDITION)
begin
insert into MyTable (Col1,Col2,Col3,Col4) values
(Val1,Val2,Val3,convert(datetime2, stuff(stuff(stuff(Val4, 17, 1, ':'), 14, 1, ':'), 11, 1, ' ')))
LOOP_VARIABLE_INCREMENT
end









share|improve this question






















  • You don't want or need dynamic sql or loops here. It seems you have data that has the rows delimited with '#' and columns delimited with a comma. You will need to split the values a second time to get columns. Why is the source data so hostile?

    – Sean Lange
    Mar 8 at 15:47













1












1








1








I have a string which I need to insert into a table after extracting values out of it. An example string is like this:



111111,1111,11.11,'2019-01-01-11.11.11.111111'#222222,2222,22.22,'2019-02-02-22.22.22.222222'


Using string_split, I can get split the values in different rows:



declare @s varchar(1000)
set @s = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222'''

select value from string_split(@s, '#')

--Output
--111111,1111,11.11,'2019-01-01-11.11.11.111111'
--222222,2222,22.22,'2019-02-02-22.22.22.222222'


It gets interesting.



The output needs to be inserted to a table. I have thought about dynamic SQL, but am not too fond of that:



declare @SQLstatment varchar(1000)
set @SQLstatment = 'insert into MyTable (Col1,Col2,Col3,Col4) values (' + OUTPUT_FROM_SPLIT + ')'
exec (@SQLstatment)


It gets more interesting.



Col4 is of DB2 data type timestamp. I need to convert it to SQL Server 2016 datetime2 data type using this statement I wrote:



declare @DB2_timpstamp varchar(30) = '2019-02-25-11.22.33.456789'
select convert(datetime2, stuff(stuff(stuff(@DB2_timpstamp, 17, 1, ':'), 14, 1, ':'), 11, 1, ' '))


Problem



I cannot make this all work.



I want to avoid using dynamic SQL as much as I can. Most probably I've to use loops. A solution will look like this:



while(SOME_CONDITION)
begin
insert into MyTable (Col1,Col2,Col3,Col4) values
(Val1,Val2,Val3,convert(datetime2, stuff(stuff(stuff(Val4, 17, 1, ':'), 14, 1, ':'), 11, 1, ' ')))
LOOP_VARIABLE_INCREMENT
end









share|improve this question














I have a string which I need to insert into a table after extracting values out of it. An example string is like this:



111111,1111,11.11,'2019-01-01-11.11.11.111111'#222222,2222,22.22,'2019-02-02-22.22.22.222222'


Using string_split, I can get split the values in different rows:



declare @s varchar(1000)
set @s = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222'''

select value from string_split(@s, '#')

--Output
--111111,1111,11.11,'2019-01-01-11.11.11.111111'
--222222,2222,22.22,'2019-02-02-22.22.22.222222'


It gets interesting.



The output needs to be inserted to a table. I have thought about dynamic SQL, but am not too fond of that:



declare @SQLstatment varchar(1000)
set @SQLstatment = 'insert into MyTable (Col1,Col2,Col3,Col4) values (' + OUTPUT_FROM_SPLIT + ')'
exec (@SQLstatment)


It gets more interesting.



Col4 is of DB2 data type timestamp. I need to convert it to SQL Server 2016 datetime2 data type using this statement I wrote:



declare @DB2_timpstamp varchar(30) = '2019-02-25-11.22.33.456789'
select convert(datetime2, stuff(stuff(stuff(@DB2_timpstamp, 17, 1, ':'), 14, 1, ':'), 11, 1, ' '))


Problem



I cannot make this all work.



I want to avoid using dynamic SQL as much as I can. Most probably I've to use loops. A solution will look like this:



while(SOME_CONDITION)
begin
insert into MyTable (Col1,Col2,Col3,Col4) values
(Val1,Val2,Val3,convert(datetime2, stuff(stuff(stuff(Val4, 17, 1, ':'), 14, 1, ':'), 11, 1, ' ')))
LOOP_VARIABLE_INCREMENT
end






sql sql-server db2 sql-server-2016






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 15:42









FarhanFarhan

1,70732243




1,70732243












  • You don't want or need dynamic sql or loops here. It seems you have data that has the rows delimited with '#' and columns delimited with a comma. You will need to split the values a second time to get columns. Why is the source data so hostile?

    – Sean Lange
    Mar 8 at 15:47

















  • You don't want or need dynamic sql or loops here. It seems you have data that has the rows delimited with '#' and columns delimited with a comma. You will need to split the values a second time to get columns. Why is the source data so hostile?

    – Sean Lange
    Mar 8 at 15:47
















You don't want or need dynamic sql or loops here. It seems you have data that has the rows delimited with '#' and columns delimited with a comma. You will need to split the values a second time to get columns. Why is the source data so hostile?

– Sean Lange
Mar 8 at 15:47





You don't want or need dynamic sql or loops here. It seems you have data that has the rows delimited with '#' and columns delimited with a comma. You will need to split the values a second time to get columns. Why is the source data so hostile?

– Sean Lange
Mar 8 at 15:47












4 Answers
4






active

oldest

votes


















1














OK, not an expert on SQL Server convertion functions but this will get you in the right track:



with 
r (value) as ( -- raw varchar value
select value from string_split(@s, '#')
),
x (col1, col2, col3, col4) as ( -- values in separate columns
select
substring(value, 1, 10) as col1, -- fix conversion here
substring(value, 11, 10) as col2, -- fix conversion here
substring(value, 21, 10) as col3, -- fix conversion here
substring(value, 31, 10) as col4, -- fix conversion here
from r
)
insert into MyTable (Col1,Col2,Col3,Col4) -- insert now
select col1, col2, col3, col4 from x


As you see, there's no need for a loop. Just normal SQL will do. Of course, you'll need to tailor the conversion formulas a bit, but this will get you pretty close.






share|improve this answer























  • Those substring pieces are not really a good approach. It needs to be a second pass through string_split.

    – Sean Lange
    Mar 8 at 16:07











  • I like this solution because it is simplest than every other one here, and I could add some other things to it too.

    – Farhan
    Mar 15 at 12:48


















2














You need to split twice:



declare @s varchar(1000)
set @s = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222'''

;WITH cte AS (
select value
from string_split(@s, '#')
)
SELECT
MAX(CASE WHEN ord=1 THEN v END) AS col1,
MAX(CASE WHEN ord=2 THEN v END) AS col2,
MAX(CASE WHEN ord=3 THEN v END) AS col3,
MAX(CASE WHEN ord=4 THEN v END) AS col4
FROM cte
CROSS APPLY (SELECT value AS v, ROW_NUMBER() OVER(ORDER BY 1/0) AS ord
FROM STRING_SPLIT([value], ',')) s
GROUP BY value;


db<>fiddle demo






share|improve this answer






























    1














    Using the power of DelimitedSplit8k_Lead you can split the items twice, and know their ordinal position (very important for pivoting). Giving you a nice simple statement of:



    DECLARE @DataSet varchar(MAX) = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222''';
    --INSERT INTO MyTable (Col1,Col2,Col3,Col4)
    SELECT MAX(CASE WHEN C.ItemNumber = 1 THEN C.item END),
    MAX(CASE WHEN C.ItemNumber = 2 THEN C.item END),
    MAX(CASE WHEN C.ItemNumber = 3 THEN C.item END),
    MAX(CASE WHEN C.ItemNumber = 4 THEN TRY_CONVERT(Datetime2(6),STUFF(STUFF(STUFF(C.item,17,1,':'),14,1,':'),11,1,'T')) END)
    FROM dbo.DelimitedSplit8K_lead(@DataSet,'#') R
    CROSS APPLY dbo.DelimitedSplit8K_lead (REPLACE(R.item,'''',''),',') C --Because we don't want those nasty single quotes!
    GROUP BY R.item;





    share|improve this answer




















    • 1





      Beat me again by about 30 seconds. Well done as always.

      – Sean Lange
      Mar 8 at 15:55











    • There's tends to always a few of us at the moment with very similar solutions all posting at the same time, @SeanLange . I find it quite amusing at times. :)

      – Larnu
      Mar 8 at 15:57



















    0














    Here's a solution that splits the string twice, and preserves the order of the columns even if they are variable length. I used this trick to preserve the order of the values returned from STRING_SPLIT. I did not preserve the order of the "rows" in the original string since it does not matter what order they are inserted in.



    DECLARE @s VARCHAR(1000) = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222''';
    DECLARE @c VARCHAR(1) = ','
    ;WITH CTE AS
    (
    SELECT s.rowNum, t.value, t.columnNum
    FROM
    (
    SELECT s.value, ROW_NUMBER() OVER(ORDER BY s.value) AS rowNum
    FROM STRING_SPLIT(@s, '#')s
    )s
    OUTER APPLY
    (
    SELECT T.VALUE, ROW_NUMBER() OVER(ORDER BY CHARINDEX(@C + t.value + @C, @C + s.value + @C))AS columnNum
    FROM STRING_SPLIT(s.value, ',') t
    )t
    )
    INSERT INTO myTable (col1, col2, col3, col4)) --do your conversions here
    SELECT MAX(CASE WHEN columnNum = 1 THEN value END), MAX(CASE WHEN columnNum = 2 THEN value END), MAX(CASE WHEN columnNum = 3 THEN value END), MAX(CASE WHEN columnNum = 4 THEN value END)
    FROM cte c
    GROUP BY rownum





    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%2f55066523%2fhow-to-insert-string-split-output-in-a-table%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









      1














      OK, not an expert on SQL Server convertion functions but this will get you in the right track:



      with 
      r (value) as ( -- raw varchar value
      select value from string_split(@s, '#')
      ),
      x (col1, col2, col3, col4) as ( -- values in separate columns
      select
      substring(value, 1, 10) as col1, -- fix conversion here
      substring(value, 11, 10) as col2, -- fix conversion here
      substring(value, 21, 10) as col3, -- fix conversion here
      substring(value, 31, 10) as col4, -- fix conversion here
      from r
      )
      insert into MyTable (Col1,Col2,Col3,Col4) -- insert now
      select col1, col2, col3, col4 from x


      As you see, there's no need for a loop. Just normal SQL will do. Of course, you'll need to tailor the conversion formulas a bit, but this will get you pretty close.






      share|improve this answer























      • Those substring pieces are not really a good approach. It needs to be a second pass through string_split.

        – Sean Lange
        Mar 8 at 16:07











      • I like this solution because it is simplest than every other one here, and I could add some other things to it too.

        – Farhan
        Mar 15 at 12:48















      1














      OK, not an expert on SQL Server convertion functions but this will get you in the right track:



      with 
      r (value) as ( -- raw varchar value
      select value from string_split(@s, '#')
      ),
      x (col1, col2, col3, col4) as ( -- values in separate columns
      select
      substring(value, 1, 10) as col1, -- fix conversion here
      substring(value, 11, 10) as col2, -- fix conversion here
      substring(value, 21, 10) as col3, -- fix conversion here
      substring(value, 31, 10) as col4, -- fix conversion here
      from r
      )
      insert into MyTable (Col1,Col2,Col3,Col4) -- insert now
      select col1, col2, col3, col4 from x


      As you see, there's no need for a loop. Just normal SQL will do. Of course, you'll need to tailor the conversion formulas a bit, but this will get you pretty close.






      share|improve this answer























      • Those substring pieces are not really a good approach. It needs to be a second pass through string_split.

        – Sean Lange
        Mar 8 at 16:07











      • I like this solution because it is simplest than every other one here, and I could add some other things to it too.

        – Farhan
        Mar 15 at 12:48













      1












      1








      1







      OK, not an expert on SQL Server convertion functions but this will get you in the right track:



      with 
      r (value) as ( -- raw varchar value
      select value from string_split(@s, '#')
      ),
      x (col1, col2, col3, col4) as ( -- values in separate columns
      select
      substring(value, 1, 10) as col1, -- fix conversion here
      substring(value, 11, 10) as col2, -- fix conversion here
      substring(value, 21, 10) as col3, -- fix conversion here
      substring(value, 31, 10) as col4, -- fix conversion here
      from r
      )
      insert into MyTable (Col1,Col2,Col3,Col4) -- insert now
      select col1, col2, col3, col4 from x


      As you see, there's no need for a loop. Just normal SQL will do. Of course, you'll need to tailor the conversion formulas a bit, but this will get you pretty close.






      share|improve this answer













      OK, not an expert on SQL Server convertion functions but this will get you in the right track:



      with 
      r (value) as ( -- raw varchar value
      select value from string_split(@s, '#')
      ),
      x (col1, col2, col3, col4) as ( -- values in separate columns
      select
      substring(value, 1, 10) as col1, -- fix conversion here
      substring(value, 11, 10) as col2, -- fix conversion here
      substring(value, 21, 10) as col3, -- fix conversion here
      substring(value, 31, 10) as col4, -- fix conversion here
      from r
      )
      insert into MyTable (Col1,Col2,Col3,Col4) -- insert now
      select col1, col2, col3, col4 from x


      As you see, there's no need for a loop. Just normal SQL will do. Of course, you'll need to tailor the conversion formulas a bit, but this will get you pretty close.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Mar 8 at 15:57









      The ImpalerThe Impaler

      11.5k41441




      11.5k41441












      • Those substring pieces are not really a good approach. It needs to be a second pass through string_split.

        – Sean Lange
        Mar 8 at 16:07











      • I like this solution because it is simplest than every other one here, and I could add some other things to it too.

        – Farhan
        Mar 15 at 12:48

















      • Those substring pieces are not really a good approach. It needs to be a second pass through string_split.

        – Sean Lange
        Mar 8 at 16:07











      • I like this solution because it is simplest than every other one here, and I could add some other things to it too.

        – Farhan
        Mar 15 at 12:48
















      Those substring pieces are not really a good approach. It needs to be a second pass through string_split.

      – Sean Lange
      Mar 8 at 16:07





      Those substring pieces are not really a good approach. It needs to be a second pass through string_split.

      – Sean Lange
      Mar 8 at 16:07













      I like this solution because it is simplest than every other one here, and I could add some other things to it too.

      – Farhan
      Mar 15 at 12:48





      I like this solution because it is simplest than every other one here, and I could add some other things to it too.

      – Farhan
      Mar 15 at 12:48













      2














      You need to split twice:



      declare @s varchar(1000)
      set @s = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222'''

      ;WITH cte AS (
      select value
      from string_split(@s, '#')
      )
      SELECT
      MAX(CASE WHEN ord=1 THEN v END) AS col1,
      MAX(CASE WHEN ord=2 THEN v END) AS col2,
      MAX(CASE WHEN ord=3 THEN v END) AS col3,
      MAX(CASE WHEN ord=4 THEN v END) AS col4
      FROM cte
      CROSS APPLY (SELECT value AS v, ROW_NUMBER() OVER(ORDER BY 1/0) AS ord
      FROM STRING_SPLIT([value], ',')) s
      GROUP BY value;


      db<>fiddle demo






      share|improve this answer



























        2














        You need to split twice:



        declare @s varchar(1000)
        set @s = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222'''

        ;WITH cte AS (
        select value
        from string_split(@s, '#')
        )
        SELECT
        MAX(CASE WHEN ord=1 THEN v END) AS col1,
        MAX(CASE WHEN ord=2 THEN v END) AS col2,
        MAX(CASE WHEN ord=3 THEN v END) AS col3,
        MAX(CASE WHEN ord=4 THEN v END) AS col4
        FROM cte
        CROSS APPLY (SELECT value AS v, ROW_NUMBER() OVER(ORDER BY 1/0) AS ord
        FROM STRING_SPLIT([value], ',')) s
        GROUP BY value;


        db<>fiddle demo






        share|improve this answer

























          2












          2








          2







          You need to split twice:



          declare @s varchar(1000)
          set @s = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222'''

          ;WITH cte AS (
          select value
          from string_split(@s, '#')
          )
          SELECT
          MAX(CASE WHEN ord=1 THEN v END) AS col1,
          MAX(CASE WHEN ord=2 THEN v END) AS col2,
          MAX(CASE WHEN ord=3 THEN v END) AS col3,
          MAX(CASE WHEN ord=4 THEN v END) AS col4
          FROM cte
          CROSS APPLY (SELECT value AS v, ROW_NUMBER() OVER(ORDER BY 1/0) AS ord
          FROM STRING_SPLIT([value], ',')) s
          GROUP BY value;


          db<>fiddle demo






          share|improve this answer













          You need to split twice:



          declare @s varchar(1000)
          set @s = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222'''

          ;WITH cte AS (
          select value
          from string_split(@s, '#')
          )
          SELECT
          MAX(CASE WHEN ord=1 THEN v END) AS col1,
          MAX(CASE WHEN ord=2 THEN v END) AS col2,
          MAX(CASE WHEN ord=3 THEN v END) AS col3,
          MAX(CASE WHEN ord=4 THEN v END) AS col4
          FROM cte
          CROSS APPLY (SELECT value AS v, ROW_NUMBER() OVER(ORDER BY 1/0) AS ord
          FROM STRING_SPLIT([value], ',')) s
          GROUP BY value;


          db<>fiddle demo







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 8 at 15:55









          Lukasz SzozdaLukasz Szozda

          82k1070110




          82k1070110





















              1














              Using the power of DelimitedSplit8k_Lead you can split the items twice, and know their ordinal position (very important for pivoting). Giving you a nice simple statement of:



              DECLARE @DataSet varchar(MAX) = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222''';
              --INSERT INTO MyTable (Col1,Col2,Col3,Col4)
              SELECT MAX(CASE WHEN C.ItemNumber = 1 THEN C.item END),
              MAX(CASE WHEN C.ItemNumber = 2 THEN C.item END),
              MAX(CASE WHEN C.ItemNumber = 3 THEN C.item END),
              MAX(CASE WHEN C.ItemNumber = 4 THEN TRY_CONVERT(Datetime2(6),STUFF(STUFF(STUFF(C.item,17,1,':'),14,1,':'),11,1,'T')) END)
              FROM dbo.DelimitedSplit8K_lead(@DataSet,'#') R
              CROSS APPLY dbo.DelimitedSplit8K_lead (REPLACE(R.item,'''',''),',') C --Because we don't want those nasty single quotes!
              GROUP BY R.item;





              share|improve this answer




















              • 1





                Beat me again by about 30 seconds. Well done as always.

                – Sean Lange
                Mar 8 at 15:55











              • There's tends to always a few of us at the moment with very similar solutions all posting at the same time, @SeanLange . I find it quite amusing at times. :)

                – Larnu
                Mar 8 at 15:57
















              1














              Using the power of DelimitedSplit8k_Lead you can split the items twice, and know their ordinal position (very important for pivoting). Giving you a nice simple statement of:



              DECLARE @DataSet varchar(MAX) = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222''';
              --INSERT INTO MyTable (Col1,Col2,Col3,Col4)
              SELECT MAX(CASE WHEN C.ItemNumber = 1 THEN C.item END),
              MAX(CASE WHEN C.ItemNumber = 2 THEN C.item END),
              MAX(CASE WHEN C.ItemNumber = 3 THEN C.item END),
              MAX(CASE WHEN C.ItemNumber = 4 THEN TRY_CONVERT(Datetime2(6),STUFF(STUFF(STUFF(C.item,17,1,':'),14,1,':'),11,1,'T')) END)
              FROM dbo.DelimitedSplit8K_lead(@DataSet,'#') R
              CROSS APPLY dbo.DelimitedSplit8K_lead (REPLACE(R.item,'''',''),',') C --Because we don't want those nasty single quotes!
              GROUP BY R.item;





              share|improve this answer




















              • 1





                Beat me again by about 30 seconds. Well done as always.

                – Sean Lange
                Mar 8 at 15:55











              • There's tends to always a few of us at the moment with very similar solutions all posting at the same time, @SeanLange . I find it quite amusing at times. :)

                – Larnu
                Mar 8 at 15:57














              1












              1








              1







              Using the power of DelimitedSplit8k_Lead you can split the items twice, and know their ordinal position (very important for pivoting). Giving you a nice simple statement of:



              DECLARE @DataSet varchar(MAX) = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222''';
              --INSERT INTO MyTable (Col1,Col2,Col3,Col4)
              SELECT MAX(CASE WHEN C.ItemNumber = 1 THEN C.item END),
              MAX(CASE WHEN C.ItemNumber = 2 THEN C.item END),
              MAX(CASE WHEN C.ItemNumber = 3 THEN C.item END),
              MAX(CASE WHEN C.ItemNumber = 4 THEN TRY_CONVERT(Datetime2(6),STUFF(STUFF(STUFF(C.item,17,1,':'),14,1,':'),11,1,'T')) END)
              FROM dbo.DelimitedSplit8K_lead(@DataSet,'#') R
              CROSS APPLY dbo.DelimitedSplit8K_lead (REPLACE(R.item,'''',''),',') C --Because we don't want those nasty single quotes!
              GROUP BY R.item;





              share|improve this answer















              Using the power of DelimitedSplit8k_Lead you can split the items twice, and know their ordinal position (very important for pivoting). Giving you a nice simple statement of:



              DECLARE @DataSet varchar(MAX) = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222''';
              --INSERT INTO MyTable (Col1,Col2,Col3,Col4)
              SELECT MAX(CASE WHEN C.ItemNumber = 1 THEN C.item END),
              MAX(CASE WHEN C.ItemNumber = 2 THEN C.item END),
              MAX(CASE WHEN C.ItemNumber = 3 THEN C.item END),
              MAX(CASE WHEN C.ItemNumber = 4 THEN TRY_CONVERT(Datetime2(6),STUFF(STUFF(STUFF(C.item,17,1,':'),14,1,':'),11,1,'T')) END)
              FROM dbo.DelimitedSplit8K_lead(@DataSet,'#') R
              CROSS APPLY dbo.DelimitedSplit8K_lead (REPLACE(R.item,'''',''),',') C --Because we don't want those nasty single quotes!
              GROUP BY R.item;






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 8 at 15:55

























              answered Mar 8 at 15:54









              LarnuLarnu

              22.3k51833




              22.3k51833







              • 1





                Beat me again by about 30 seconds. Well done as always.

                – Sean Lange
                Mar 8 at 15:55











              • There's tends to always a few of us at the moment with very similar solutions all posting at the same time, @SeanLange . I find it quite amusing at times. :)

                – Larnu
                Mar 8 at 15:57













              • 1





                Beat me again by about 30 seconds. Well done as always.

                – Sean Lange
                Mar 8 at 15:55











              • There's tends to always a few of us at the moment with very similar solutions all posting at the same time, @SeanLange . I find it quite amusing at times. :)

                – Larnu
                Mar 8 at 15:57








              1




              1





              Beat me again by about 30 seconds. Well done as always.

              – Sean Lange
              Mar 8 at 15:55





              Beat me again by about 30 seconds. Well done as always.

              – Sean Lange
              Mar 8 at 15:55













              There's tends to always a few of us at the moment with very similar solutions all posting at the same time, @SeanLange . I find it quite amusing at times. :)

              – Larnu
              Mar 8 at 15:57






              There's tends to always a few of us at the moment with very similar solutions all posting at the same time, @SeanLange . I find it quite amusing at times. :)

              – Larnu
              Mar 8 at 15:57












              0














              Here's a solution that splits the string twice, and preserves the order of the columns even if they are variable length. I used this trick to preserve the order of the values returned from STRING_SPLIT. I did not preserve the order of the "rows" in the original string since it does not matter what order they are inserted in.



              DECLARE @s VARCHAR(1000) = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222''';
              DECLARE @c VARCHAR(1) = ','
              ;WITH CTE AS
              (
              SELECT s.rowNum, t.value, t.columnNum
              FROM
              (
              SELECT s.value, ROW_NUMBER() OVER(ORDER BY s.value) AS rowNum
              FROM STRING_SPLIT(@s, '#')s
              )s
              OUTER APPLY
              (
              SELECT T.VALUE, ROW_NUMBER() OVER(ORDER BY CHARINDEX(@C + t.value + @C, @C + s.value + @C))AS columnNum
              FROM STRING_SPLIT(s.value, ',') t
              )t
              )
              INSERT INTO myTable (col1, col2, col3, col4)) --do your conversions here
              SELECT MAX(CASE WHEN columnNum = 1 THEN value END), MAX(CASE WHEN columnNum = 2 THEN value END), MAX(CASE WHEN columnNum = 3 THEN value END), MAX(CASE WHEN columnNum = 4 THEN value END)
              FROM cte c
              GROUP BY rownum





              share|improve this answer



























                0














                Here's a solution that splits the string twice, and preserves the order of the columns even if they are variable length. I used this trick to preserve the order of the values returned from STRING_SPLIT. I did not preserve the order of the "rows" in the original string since it does not matter what order they are inserted in.



                DECLARE @s VARCHAR(1000) = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222''';
                DECLARE @c VARCHAR(1) = ','
                ;WITH CTE AS
                (
                SELECT s.rowNum, t.value, t.columnNum
                FROM
                (
                SELECT s.value, ROW_NUMBER() OVER(ORDER BY s.value) AS rowNum
                FROM STRING_SPLIT(@s, '#')s
                )s
                OUTER APPLY
                (
                SELECT T.VALUE, ROW_NUMBER() OVER(ORDER BY CHARINDEX(@C + t.value + @C, @C + s.value + @C))AS columnNum
                FROM STRING_SPLIT(s.value, ',') t
                )t
                )
                INSERT INTO myTable (col1, col2, col3, col4)) --do your conversions here
                SELECT MAX(CASE WHEN columnNum = 1 THEN value END), MAX(CASE WHEN columnNum = 2 THEN value END), MAX(CASE WHEN columnNum = 3 THEN value END), MAX(CASE WHEN columnNum = 4 THEN value END)
                FROM cte c
                GROUP BY rownum





                share|improve this answer

























                  0












                  0








                  0







                  Here's a solution that splits the string twice, and preserves the order of the columns even if they are variable length. I used this trick to preserve the order of the values returned from STRING_SPLIT. I did not preserve the order of the "rows" in the original string since it does not matter what order they are inserted in.



                  DECLARE @s VARCHAR(1000) = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222''';
                  DECLARE @c VARCHAR(1) = ','
                  ;WITH CTE AS
                  (
                  SELECT s.rowNum, t.value, t.columnNum
                  FROM
                  (
                  SELECT s.value, ROW_NUMBER() OVER(ORDER BY s.value) AS rowNum
                  FROM STRING_SPLIT(@s, '#')s
                  )s
                  OUTER APPLY
                  (
                  SELECT T.VALUE, ROW_NUMBER() OVER(ORDER BY CHARINDEX(@C + t.value + @C, @C + s.value + @C))AS columnNum
                  FROM STRING_SPLIT(s.value, ',') t
                  )t
                  )
                  INSERT INTO myTable (col1, col2, col3, col4)) --do your conversions here
                  SELECT MAX(CASE WHEN columnNum = 1 THEN value END), MAX(CASE WHEN columnNum = 2 THEN value END), MAX(CASE WHEN columnNum = 3 THEN value END), MAX(CASE WHEN columnNum = 4 THEN value END)
                  FROM cte c
                  GROUP BY rownum





                  share|improve this answer













                  Here's a solution that splits the string twice, and preserves the order of the columns even if they are variable length. I used this trick to preserve the order of the values returned from STRING_SPLIT. I did not preserve the order of the "rows" in the original string since it does not matter what order they are inserted in.



                  DECLARE @s VARCHAR(1000) = '111111,1111,11.11,''2019-01-01-11.11.11.111111''#222222,2222,22.22,''2019-02-02-22.22.22.222222''';
                  DECLARE @c VARCHAR(1) = ','
                  ;WITH CTE AS
                  (
                  SELECT s.rowNum, t.value, t.columnNum
                  FROM
                  (
                  SELECT s.value, ROW_NUMBER() OVER(ORDER BY s.value) AS rowNum
                  FROM STRING_SPLIT(@s, '#')s
                  )s
                  OUTER APPLY
                  (
                  SELECT T.VALUE, ROW_NUMBER() OVER(ORDER BY CHARINDEX(@C + t.value + @C, @C + s.value + @C))AS columnNum
                  FROM STRING_SPLIT(s.value, ',') t
                  )t
                  )
                  INSERT INTO myTable (col1, col2, col3, col4)) --do your conversions here
                  SELECT MAX(CASE WHEN columnNum = 1 THEN value END), MAX(CASE WHEN columnNum = 2 THEN value END), MAX(CASE WHEN columnNum = 3 THEN value END), MAX(CASE WHEN columnNum = 4 THEN value END)
                  FROM cte c
                  GROUP BY rownum






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 8 at 16:15









                  elizabkelizabk

                  280110




                  280110



























                      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%2f55066523%2fhow-to-insert-string-split-output-in-a-table%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

                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived