Grabbing each row's Data and setting it to Variable - TSQLIs there a way to loop through a table variable in TSQL without using a cursor?How do I generate random number for each row in a TSQL Select?How to set variable from a SQL query?Access Stored Procedure Parameters with Dynamic SQLRows to comma separated, vertical to horizontal, values in SQL ServerSQL Select Multiple Part of string!SQL statement which returns id and splits comma separated valuesHow to eliminate Nulls, and insert with split delimterCursor Usage in SQL ServerHow can I retrieve first second and third word of a String in SQL?

What would be the challenges to taking off and landing a typical passenger jet at FL300?

Why in most German places is the church the tallest building?

Compelling story with the world as a villain

Architectural feasibility of a tiered circular stone keep

Why do gliders have bungee cords in the control systems and what do they do? Are they on all control surfaces? What about ultralights?

What is the difference between "Grippe" and "Männergrippe"?

Are modern clipless shoes and pedals that much better than toe clips and straps?

Is it possible to perform a regression where you have an unknown / unknowable feature variable?

Command in bash shell script to find path to that script?

Prove your innocence

How to gently end involvement with an online community?

LeetCode: Group Anagrams C#

How do I request a longer than normal leave of absence period for my wedding?

Can a Rogue PC teach an NPC to perform Sneak Attack?

What is a CirKle Word™?

I don't have the theoretical background in my PhD topic. I can't justify getting the degree

Would it be possible to have a GMO that produces chocolate?

Why did MS-DOS applications built using Turbo Pascal fail to start with a division by zero error on faster systems?

Why doesn't 'd /= d' throw a division by zero exception?

Why do banks “park” their money at the European Central Bank?

Is there any method of inflicting the incapacitated condition and no other condition?

Why did this happen to Thanos's ships at the end of "Avengers: Endgame"?

Converting a set into a string

Handling Disruptive Student on the Autistic Spectrum



Grabbing each row's Data and setting it to Variable - TSQL


Is there a way to loop through a table variable in TSQL without using a cursor?How do I generate random number for each row in a TSQL Select?How to set variable from a SQL query?Access Stored Procedure Parameters with Dynamic SQLRows to comma separated, vertical to horizontal, values in SQL ServerSQL Select Multiple Part of string!SQL statement which returns id and splits comma separated valuesHow to eliminate Nulls, and insert with split delimterCursor Usage in SQL ServerHow can I retrieve first second and third word of a String in SQL?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm trying to create a loop that will pull out one value of a row and store it to a variable(@nameString). I need this to happen for an unknown amount of rows. What should I be referring to when I'm I need this loop to cycle through all of the rows and update my variable each time it loops with the next rows value.



I have tried a few counter loops and they do not cycle through the rows they just keep hitting the same one.



-- Code for parsing a name with multiple parts

DECLARE @nameString as varchar(max),
@firstSpaceLoc as smallint,
@secondSpaceLoc as smallint,
@thirdSpaceLoc as smallint,
@firstString as varchar(max),
@secondString as varchar(max),
@thirdString as varchar(max)

-- I'm expecting the loop to be below here!
SET @nameString = 'Robert Dobson, Jr.'
--SET @nameString = 'Robert William Dobson, Sr.'

-- How many strings are in the name?
-- Is there one space in the name
SET @firstSpaceLoc = CHARINDEX(' ',@namestring,1)

-- Is there second space in the name
SET @secondSpaceLoc = CHARINDEX(' ', @namestring, CHARINDEX(' ',@nameString,1)+1)

-- Is there a third space in the name
SET @thirdSpaceLoc =
CASE
WHEN CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1) = 0 THEN 0
WHEN CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1) > 0 THEN
CHARINDEX(' ', @namestring,
CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1)+1)
END

SELECT
@nameString sourceString,
CASE
WHEN @firstSpaceLoc > 0 THEN 'There is one space'
ELSE 'There is not one space'
END [Is there one space],
CASE
WHEN @secondSpaceLoc > 0 THEN 'There is a second space'
ELSE 'There is not a second space'
END [Is there a second space],
CASE
WHEN @thirdSpaceLoc > 0 THEN 'There is a third space'
ELSE 'There is not a third space'
END [Is there a third space]


-- extract and save strings
SELECT

@firstString =
CASE
WHEN @firstSpaceLoc > 0 THEN LEFT(@nameString,CHARINDEX(' ',@namestring,1)-1)
ELSE @nameString
END,
@secondString =
CASE
WHEN @firstSpaceLoc = 0 THEN ''
WHEN @secondSpaceLoc = 0 THEN
RIGHT(@namestring, LEN(@namestring)- CHARINDEX(' ',@namestring,1))
WHEN @secondSpaceLoc > 0 THEN
REPLACE (
SUBSTRING (
@nameString,
CHARINDEX(' ',@namestring,1)+1,
CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1)
- CHARINDEX(' ',@namestring,1)
),
',',
''
)
ELSE ''
END,
@thirdString =
CASE
WHEN @firstSpaceLoc = 0 OR @secondSpaceLoc = 0 THEN ''
WHEN @secondSpaceLoc > 0
AND @thirdSpaceLoc = 0 THEN
SUBSTRING (
@nameString,
CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1)+1,
LEN(@nameString)
)
ELSE RIGHT(@namestring,LEN(@namestring) - @secondSpaceLoc)
END


-- Report names
SELECT
@nameString sourceString,
@firstString [First string],
@secondString [Second string],
@thirdString [Third string]

SELECT
CASE
WHEN @thirdSpaceLoc > 0 THEN
@thirdString + ', ' + @firstString + ' ' + @secondString
WHEN @secondSpaceLoc > 0 AND @thirdSpaceLoc = 0 THEN
@secondString + ' ' + @thirdString + ', ' + @firstString
WHEN @firstSpaceLoc > 0 THEN
@secondString + ', ' + @firstString
WHEN @firstSpaceLoc = 0 THEN
@firstString
END [Reported Name]


Expected results is that this goes through and separate every row in a column with multiple spaces to a long list of name that are separated. This list but a lot longer.enter image description here










share|improve this question


























  • Is another application calling this query/procedure? Or is this just meant to run inside of SQL-Server?

    – Ryan Wilson
    Mar 27 at 17:29











  • It is just meant to run in SQL server. No SP or applications

    – NeoAer
    Mar 27 at 17:30











  • Why do you think you need a loop? They are horribly inefficient.

    – Sean Lange
    Mar 27 at 17:37











  • Why not use STRING_SPLIT, then PIVOT your result?

    – Robert Sievers
    Mar 27 at 17:37











  • No the above code works just fine if copied into T-SQL as a standalone. The issue i'm having trying to figure out is how to loop this and capture each rows information.

    – NeoAer
    Mar 27 at 17:39

















0















I'm trying to create a loop that will pull out one value of a row and store it to a variable(@nameString). I need this to happen for an unknown amount of rows. What should I be referring to when I'm I need this loop to cycle through all of the rows and update my variable each time it loops with the next rows value.



I have tried a few counter loops and they do not cycle through the rows they just keep hitting the same one.



-- Code for parsing a name with multiple parts

DECLARE @nameString as varchar(max),
@firstSpaceLoc as smallint,
@secondSpaceLoc as smallint,
@thirdSpaceLoc as smallint,
@firstString as varchar(max),
@secondString as varchar(max),
@thirdString as varchar(max)

-- I'm expecting the loop to be below here!
SET @nameString = 'Robert Dobson, Jr.'
--SET @nameString = 'Robert William Dobson, Sr.'

-- How many strings are in the name?
-- Is there one space in the name
SET @firstSpaceLoc = CHARINDEX(' ',@namestring,1)

-- Is there second space in the name
SET @secondSpaceLoc = CHARINDEX(' ', @namestring, CHARINDEX(' ',@nameString,1)+1)

-- Is there a third space in the name
SET @thirdSpaceLoc =
CASE
WHEN CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1) = 0 THEN 0
WHEN CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1) > 0 THEN
CHARINDEX(' ', @namestring,
CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1)+1)
END

SELECT
@nameString sourceString,
CASE
WHEN @firstSpaceLoc > 0 THEN 'There is one space'
ELSE 'There is not one space'
END [Is there one space],
CASE
WHEN @secondSpaceLoc > 0 THEN 'There is a second space'
ELSE 'There is not a second space'
END [Is there a second space],
CASE
WHEN @thirdSpaceLoc > 0 THEN 'There is a third space'
ELSE 'There is not a third space'
END [Is there a third space]


-- extract and save strings
SELECT

@firstString =
CASE
WHEN @firstSpaceLoc > 0 THEN LEFT(@nameString,CHARINDEX(' ',@namestring,1)-1)
ELSE @nameString
END,
@secondString =
CASE
WHEN @firstSpaceLoc = 0 THEN ''
WHEN @secondSpaceLoc = 0 THEN
RIGHT(@namestring, LEN(@namestring)- CHARINDEX(' ',@namestring,1))
WHEN @secondSpaceLoc > 0 THEN
REPLACE (
SUBSTRING (
@nameString,
CHARINDEX(' ',@namestring,1)+1,
CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1)
- CHARINDEX(' ',@namestring,1)
),
',',
''
)
ELSE ''
END,
@thirdString =
CASE
WHEN @firstSpaceLoc = 0 OR @secondSpaceLoc = 0 THEN ''
WHEN @secondSpaceLoc > 0
AND @thirdSpaceLoc = 0 THEN
SUBSTRING (
@nameString,
CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1)+1,
LEN(@nameString)
)
ELSE RIGHT(@namestring,LEN(@namestring) - @secondSpaceLoc)
END


-- Report names
SELECT
@nameString sourceString,
@firstString [First string],
@secondString [Second string],
@thirdString [Third string]

SELECT
CASE
WHEN @thirdSpaceLoc > 0 THEN
@thirdString + ', ' + @firstString + ' ' + @secondString
WHEN @secondSpaceLoc > 0 AND @thirdSpaceLoc = 0 THEN
@secondString + ' ' + @thirdString + ', ' + @firstString
WHEN @firstSpaceLoc > 0 THEN
@secondString + ', ' + @firstString
WHEN @firstSpaceLoc = 0 THEN
@firstString
END [Reported Name]


Expected results is that this goes through and separate every row in a column with multiple spaces to a long list of name that are separated. This list but a lot longer.enter image description here










share|improve this question


























  • Is another application calling this query/procedure? Or is this just meant to run inside of SQL-Server?

    – Ryan Wilson
    Mar 27 at 17:29











  • It is just meant to run in SQL server. No SP or applications

    – NeoAer
    Mar 27 at 17:30











  • Why do you think you need a loop? They are horribly inefficient.

    – Sean Lange
    Mar 27 at 17:37











  • Why not use STRING_SPLIT, then PIVOT your result?

    – Robert Sievers
    Mar 27 at 17:37











  • No the above code works just fine if copied into T-SQL as a standalone. The issue i'm having trying to figure out is how to loop this and capture each rows information.

    – NeoAer
    Mar 27 at 17:39













0












0








0








I'm trying to create a loop that will pull out one value of a row and store it to a variable(@nameString). I need this to happen for an unknown amount of rows. What should I be referring to when I'm I need this loop to cycle through all of the rows and update my variable each time it loops with the next rows value.



I have tried a few counter loops and they do not cycle through the rows they just keep hitting the same one.



-- Code for parsing a name with multiple parts

DECLARE @nameString as varchar(max),
@firstSpaceLoc as smallint,
@secondSpaceLoc as smallint,
@thirdSpaceLoc as smallint,
@firstString as varchar(max),
@secondString as varchar(max),
@thirdString as varchar(max)

-- I'm expecting the loop to be below here!
SET @nameString = 'Robert Dobson, Jr.'
--SET @nameString = 'Robert William Dobson, Sr.'

-- How many strings are in the name?
-- Is there one space in the name
SET @firstSpaceLoc = CHARINDEX(' ',@namestring,1)

-- Is there second space in the name
SET @secondSpaceLoc = CHARINDEX(' ', @namestring, CHARINDEX(' ',@nameString,1)+1)

-- Is there a third space in the name
SET @thirdSpaceLoc =
CASE
WHEN CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1) = 0 THEN 0
WHEN CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1) > 0 THEN
CHARINDEX(' ', @namestring,
CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1)+1)
END

SELECT
@nameString sourceString,
CASE
WHEN @firstSpaceLoc > 0 THEN 'There is one space'
ELSE 'There is not one space'
END [Is there one space],
CASE
WHEN @secondSpaceLoc > 0 THEN 'There is a second space'
ELSE 'There is not a second space'
END [Is there a second space],
CASE
WHEN @thirdSpaceLoc > 0 THEN 'There is a third space'
ELSE 'There is not a third space'
END [Is there a third space]


-- extract and save strings
SELECT

@firstString =
CASE
WHEN @firstSpaceLoc > 0 THEN LEFT(@nameString,CHARINDEX(' ',@namestring,1)-1)
ELSE @nameString
END,
@secondString =
CASE
WHEN @firstSpaceLoc = 0 THEN ''
WHEN @secondSpaceLoc = 0 THEN
RIGHT(@namestring, LEN(@namestring)- CHARINDEX(' ',@namestring,1))
WHEN @secondSpaceLoc > 0 THEN
REPLACE (
SUBSTRING (
@nameString,
CHARINDEX(' ',@namestring,1)+1,
CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1)
- CHARINDEX(' ',@namestring,1)
),
',',
''
)
ELSE ''
END,
@thirdString =
CASE
WHEN @firstSpaceLoc = 0 OR @secondSpaceLoc = 0 THEN ''
WHEN @secondSpaceLoc > 0
AND @thirdSpaceLoc = 0 THEN
SUBSTRING (
@nameString,
CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1)+1,
LEN(@nameString)
)
ELSE RIGHT(@namestring,LEN(@namestring) - @secondSpaceLoc)
END


-- Report names
SELECT
@nameString sourceString,
@firstString [First string],
@secondString [Second string],
@thirdString [Third string]

SELECT
CASE
WHEN @thirdSpaceLoc > 0 THEN
@thirdString + ', ' + @firstString + ' ' + @secondString
WHEN @secondSpaceLoc > 0 AND @thirdSpaceLoc = 0 THEN
@secondString + ' ' + @thirdString + ', ' + @firstString
WHEN @firstSpaceLoc > 0 THEN
@secondString + ', ' + @firstString
WHEN @firstSpaceLoc = 0 THEN
@firstString
END [Reported Name]


Expected results is that this goes through and separate every row in a column with multiple spaces to a long list of name that are separated. This list but a lot longer.enter image description here










share|improve this question
















I'm trying to create a loop that will pull out one value of a row and store it to a variable(@nameString). I need this to happen for an unknown amount of rows. What should I be referring to when I'm I need this loop to cycle through all of the rows and update my variable each time it loops with the next rows value.



I have tried a few counter loops and they do not cycle through the rows they just keep hitting the same one.



-- Code for parsing a name with multiple parts

DECLARE @nameString as varchar(max),
@firstSpaceLoc as smallint,
@secondSpaceLoc as smallint,
@thirdSpaceLoc as smallint,
@firstString as varchar(max),
@secondString as varchar(max),
@thirdString as varchar(max)

-- I'm expecting the loop to be below here!
SET @nameString = 'Robert Dobson, Jr.'
--SET @nameString = 'Robert William Dobson, Sr.'

-- How many strings are in the name?
-- Is there one space in the name
SET @firstSpaceLoc = CHARINDEX(' ',@namestring,1)

-- Is there second space in the name
SET @secondSpaceLoc = CHARINDEX(' ', @namestring, CHARINDEX(' ',@nameString,1)+1)

-- Is there a third space in the name
SET @thirdSpaceLoc =
CASE
WHEN CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1) = 0 THEN 0
WHEN CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1) > 0 THEN
CHARINDEX(' ', @namestring,
CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1)+1)
END

SELECT
@nameString sourceString,
CASE
WHEN @firstSpaceLoc > 0 THEN 'There is one space'
ELSE 'There is not one space'
END [Is there one space],
CASE
WHEN @secondSpaceLoc > 0 THEN 'There is a second space'
ELSE 'There is not a second space'
END [Is there a second space],
CASE
WHEN @thirdSpaceLoc > 0 THEN 'There is a third space'
ELSE 'There is not a third space'
END [Is there a third space]


-- extract and save strings
SELECT

@firstString =
CASE
WHEN @firstSpaceLoc > 0 THEN LEFT(@nameString,CHARINDEX(' ',@namestring,1)-1)
ELSE @nameString
END,
@secondString =
CASE
WHEN @firstSpaceLoc = 0 THEN ''
WHEN @secondSpaceLoc = 0 THEN
RIGHT(@namestring, LEN(@namestring)- CHARINDEX(' ',@namestring,1))
WHEN @secondSpaceLoc > 0 THEN
REPLACE (
SUBSTRING (
@nameString,
CHARINDEX(' ',@namestring,1)+1,
CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1)
- CHARINDEX(' ',@namestring,1)
),
',',
''
)
ELSE ''
END,
@thirdString =
CASE
WHEN @firstSpaceLoc = 0 OR @secondSpaceLoc = 0 THEN ''
WHEN @secondSpaceLoc > 0
AND @thirdSpaceLoc = 0 THEN
SUBSTRING (
@nameString,
CHARINDEX(' ', @namestring,
CHARINDEX(' ',@nameString,1)+1)+1,
LEN(@nameString)
)
ELSE RIGHT(@namestring,LEN(@namestring) - @secondSpaceLoc)
END


-- Report names
SELECT
@nameString sourceString,
@firstString [First string],
@secondString [Second string],
@thirdString [Third string]

SELECT
CASE
WHEN @thirdSpaceLoc > 0 THEN
@thirdString + ', ' + @firstString + ' ' + @secondString
WHEN @secondSpaceLoc > 0 AND @thirdSpaceLoc = 0 THEN
@secondString + ' ' + @thirdString + ', ' + @firstString
WHEN @firstSpaceLoc > 0 THEN
@secondString + ', ' + @firstString
WHEN @firstSpaceLoc = 0 THEN
@firstString
END [Reported Name]


Expected results is that this goes through and separate every row in a column with multiple spaces to a long list of name that are separated. This list but a lot longer.enter image description here







sql-server tsql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 17:47







NeoAer

















asked Mar 27 at 17:25









NeoAerNeoAer

758 bronze badges




758 bronze badges















  • Is another application calling this query/procedure? Or is this just meant to run inside of SQL-Server?

    – Ryan Wilson
    Mar 27 at 17:29











  • It is just meant to run in SQL server. No SP or applications

    – NeoAer
    Mar 27 at 17:30











  • Why do you think you need a loop? They are horribly inefficient.

    – Sean Lange
    Mar 27 at 17:37











  • Why not use STRING_SPLIT, then PIVOT your result?

    – Robert Sievers
    Mar 27 at 17:37











  • No the above code works just fine if copied into T-SQL as a standalone. The issue i'm having trying to figure out is how to loop this and capture each rows information.

    – NeoAer
    Mar 27 at 17:39

















  • Is another application calling this query/procedure? Or is this just meant to run inside of SQL-Server?

    – Ryan Wilson
    Mar 27 at 17:29











  • It is just meant to run in SQL server. No SP or applications

    – NeoAer
    Mar 27 at 17:30











  • Why do you think you need a loop? They are horribly inefficient.

    – Sean Lange
    Mar 27 at 17:37











  • Why not use STRING_SPLIT, then PIVOT your result?

    – Robert Sievers
    Mar 27 at 17:37











  • No the above code works just fine if copied into T-SQL as a standalone. The issue i'm having trying to figure out is how to loop this and capture each rows information.

    – NeoAer
    Mar 27 at 17:39
















Is another application calling this query/procedure? Or is this just meant to run inside of SQL-Server?

– Ryan Wilson
Mar 27 at 17:29





Is another application calling this query/procedure? Or is this just meant to run inside of SQL-Server?

– Ryan Wilson
Mar 27 at 17:29













It is just meant to run in SQL server. No SP or applications

– NeoAer
Mar 27 at 17:30





It is just meant to run in SQL server. No SP or applications

– NeoAer
Mar 27 at 17:30













Why do you think you need a loop? They are horribly inefficient.

– Sean Lange
Mar 27 at 17:37





Why do you think you need a loop? They are horribly inefficient.

– Sean Lange
Mar 27 at 17:37













Why not use STRING_SPLIT, then PIVOT your result?

– Robert Sievers
Mar 27 at 17:37





Why not use STRING_SPLIT, then PIVOT your result?

– Robert Sievers
Mar 27 at 17:37













No the above code works just fine if copied into T-SQL as a standalone. The issue i'm having trying to figure out is how to loop this and capture each rows information.

– NeoAer
Mar 27 at 17:39





No the above code works just fine if copied into T-SQL as a standalone. The issue i'm having trying to figure out is how to loop this and capture each rows information.

– NeoAer
Mar 27 at 17:39












3 Answers
3






active

oldest

votes


















0















can you try this way:



DECLARE @nameString AS VARCHAR(MAX), 
@firstString AS VARCHAR(MAX),
@secondString AS VARCHAR(MAX),
@thirdString AS VARCHAR(MAX)

SET @nameString = 'Robert Dobson, Jr.'

DECLARE @tbl TABLE
(
Id INT IDENTITY(1,1),
Name VARCHAR(MAX)
)

INSERT INTO @tbl(Name)
SELECT value FROM STRING_SPLIT(@nameString, ' ');


SELECT @firstString = Name FROM @tbl WHERE Id = 1
SELECT @secondString = Name FROM @tbl WHERE Id = 2
SELECT @thirdString = Name FROM @tbl WHERE Id = 3


SELECT
@nameString sourceString,
CASE WHEN LEN(@firstString) > 0 THEN 'There is one space'
ELSE 'There is not one space'
END [Is there one space],
CASE WHEN LEN(@secondString)> 0 THEN 'There is a second space'
ELSE 'There is not a second space'
END [Is there a second space],
CASE WHEN LEN(@thirdString)> 0 THEN 'There is a third space'
ELSE 'There is not a third space'
END [Is there a third space]

SELECT @nameString SourceString, @firstString [First string], @secondString [Second string] , @thirdString [Third string]

SELECT
CASE
WHEN LEN(@thirdString) > 0 THEN
@thirdString + ', ' + @firstString + ' ' + @secondString
WHEN LEN(@secondString) > 0 AND LEN(@thirdString) = 0 THEN
@secondString + ' ' + @thirdString + ', ' + @firstString
WHEN LEN(@firstString) > 0 THEN
@secondString + ', ' + @firstString
WHEN LEN(@firstString) = 0 THEN
@firstString
END [Reported Name]





share|improve this answer
































    0















    Sorry if there is some bug in the code, I don't have access to MS-SQL now I've tried to coded directly here.
    Your request is quite unusual (I agree with Robert's comment) , but a code simple like this would work.



    DECLARE @nameString as varchar(max),
    @firstString as varchar(max),
    @secondString as varchar(max),
    @thirdString as varchar(max)

    SET @nameString = 'Robert Dobson, Jr.'

    SET @thirdString = REPLACE(@nameString, ',', '')
    SET @firstString = LTRIM(SUBSTRING(@thirdString, 1, CHARINDEX(' ', @thirdString)))
    SET @thirdString = LTRIM(REPLACE(@thirdString, @firstString, ‘’))
    SET @secondString = LTRIM(SUBSTRING(@thirdString, 1, CHARINDEX(' ', @thirdString)))
    SET @thirdString = LTRIM(REPLACE(@thirdString, @secondString, ‘’))

    SELECT
    @nameString sourceString,
    @firstString [First string],
    @secondString [Second string],
    @thirdString [Third string]





    share|improve this answer
































      0















      I am making the assumption that you need this to return a dynamic number of columns based on the number of spaces found in nameString. I am using a couple of things there that you will need on your system for this to work correctly.



      First is a tally table. I keep one on my systems as a view. Here is the code that I use for this. A tally table is a great tool to help us avoid using loops. You can read more about them here.



      create View [dbo].[cteTally] as

      WITH
      E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
      E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
      E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
      cteTally(N) AS
      (
      SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
      )
      select N from cteTally


      The next thing we need is a string splitter. There are a number of these out there and even a built in one on recent versions of sql server. However, even the MS one misses a critical element of ordinal position for each element. Fortunately Jeff Moden has one that is set based, lightning fast and returns the position number of each element.



      You can find the code for the DelimitedSplit8K here.



      Now we face the challenge of returning a dynamic number of columns. For this you could use a dynamic pivot. That will work just fine. For me I find the syntax for pivot to very obtuse and prefer to use conditional aggregation, or crosstab. In this case it needs to be dynamic.



      I created a temp table in my example to represent your table. I included some additional names to the list and some of them have more than 3 strings.



      if OBJECT_ID('tempdb..#Something') is not null
      drop table #Something

      create table #Something --this represents your current table
      (
      nameString varchar(100)
      )

      insert #Something values
      ('Robert Dobson, Jr.')
      , ('NeoAer')
      , ('Ryan Wilson')
      , ('Somebody with four names')
      , ('another with yet more names')

      declare @StaticPortion nvarchar(2000) =
      'with OrderedResults as
      (
      select nameString
      , stringValue = replace(x.Item, '','', '''')
      , x.ItemNumber
      from #Something s
      cross apply dbo.DelimitedSplit8K(s.nameString, '' '') x
      )
      select nameString';

      declare @DynamicPortion nvarchar(max) = '';
      declare @FinalStaticPortion nvarchar(2000) = ' from OrderedResults Group by nameString order by nameString';

      select @DynamicPortion = @DynamicPortion +
      ', MAX(Case when ItemNumber = ' + CAST(N as varchar(6)) + ' then stringValue end) as string' + CAST(N as varchar(6)) + CHAR(10)
      from cteTally t
      where t.N <=
      (
      select top 1 Count(*)
      from #Something s
      cross apply dbo.DelimitedSplit8K(s.nameString, ' ') x
      group by nameString
      order by COUNT(*) desc
      )

      select @StaticPortion + @DynamicPortion + @FinalStaticPortion

      --once you are satisfied that the dynamic sql is correct uncomment the next two lines to execute it.
      --declare @SqlToExecute nvarchar(max) = @StaticPortion + @DynamicPortion + @FinalStaticPortion;
      --exec sp_executesql @SqlToExecute


      If you don't this to return a dynamic number of columns we can employ a similar type of query but it far less complicated.






      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%2f55383213%2fgrabbing-each-rows-data-and-setting-it-to-variable-tsql%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0















        can you try this way:



        DECLARE @nameString AS VARCHAR(MAX), 
        @firstString AS VARCHAR(MAX),
        @secondString AS VARCHAR(MAX),
        @thirdString AS VARCHAR(MAX)

        SET @nameString = 'Robert Dobson, Jr.'

        DECLARE @tbl TABLE
        (
        Id INT IDENTITY(1,1),
        Name VARCHAR(MAX)
        )

        INSERT INTO @tbl(Name)
        SELECT value FROM STRING_SPLIT(@nameString, ' ');


        SELECT @firstString = Name FROM @tbl WHERE Id = 1
        SELECT @secondString = Name FROM @tbl WHERE Id = 2
        SELECT @thirdString = Name FROM @tbl WHERE Id = 3


        SELECT
        @nameString sourceString,
        CASE WHEN LEN(@firstString) > 0 THEN 'There is one space'
        ELSE 'There is not one space'
        END [Is there one space],
        CASE WHEN LEN(@secondString)> 0 THEN 'There is a second space'
        ELSE 'There is not a second space'
        END [Is there a second space],
        CASE WHEN LEN(@thirdString)> 0 THEN 'There is a third space'
        ELSE 'There is not a third space'
        END [Is there a third space]

        SELECT @nameString SourceString, @firstString [First string], @secondString [Second string] , @thirdString [Third string]

        SELECT
        CASE
        WHEN LEN(@thirdString) > 0 THEN
        @thirdString + ', ' + @firstString + ' ' + @secondString
        WHEN LEN(@secondString) > 0 AND LEN(@thirdString) = 0 THEN
        @secondString + ' ' + @thirdString + ', ' + @firstString
        WHEN LEN(@firstString) > 0 THEN
        @secondString + ', ' + @firstString
        WHEN LEN(@firstString) = 0 THEN
        @firstString
        END [Reported Name]





        share|improve this answer





























          0















          can you try this way:



          DECLARE @nameString AS VARCHAR(MAX), 
          @firstString AS VARCHAR(MAX),
          @secondString AS VARCHAR(MAX),
          @thirdString AS VARCHAR(MAX)

          SET @nameString = 'Robert Dobson, Jr.'

          DECLARE @tbl TABLE
          (
          Id INT IDENTITY(1,1),
          Name VARCHAR(MAX)
          )

          INSERT INTO @tbl(Name)
          SELECT value FROM STRING_SPLIT(@nameString, ' ');


          SELECT @firstString = Name FROM @tbl WHERE Id = 1
          SELECT @secondString = Name FROM @tbl WHERE Id = 2
          SELECT @thirdString = Name FROM @tbl WHERE Id = 3


          SELECT
          @nameString sourceString,
          CASE WHEN LEN(@firstString) > 0 THEN 'There is one space'
          ELSE 'There is not one space'
          END [Is there one space],
          CASE WHEN LEN(@secondString)> 0 THEN 'There is a second space'
          ELSE 'There is not a second space'
          END [Is there a second space],
          CASE WHEN LEN(@thirdString)> 0 THEN 'There is a third space'
          ELSE 'There is not a third space'
          END [Is there a third space]

          SELECT @nameString SourceString, @firstString [First string], @secondString [Second string] , @thirdString [Third string]

          SELECT
          CASE
          WHEN LEN(@thirdString) > 0 THEN
          @thirdString + ', ' + @firstString + ' ' + @secondString
          WHEN LEN(@secondString) > 0 AND LEN(@thirdString) = 0 THEN
          @secondString + ' ' + @thirdString + ', ' + @firstString
          WHEN LEN(@firstString) > 0 THEN
          @secondString + ', ' + @firstString
          WHEN LEN(@firstString) = 0 THEN
          @firstString
          END [Reported Name]





          share|improve this answer



























            0














            0










            0









            can you try this way:



            DECLARE @nameString AS VARCHAR(MAX), 
            @firstString AS VARCHAR(MAX),
            @secondString AS VARCHAR(MAX),
            @thirdString AS VARCHAR(MAX)

            SET @nameString = 'Robert Dobson, Jr.'

            DECLARE @tbl TABLE
            (
            Id INT IDENTITY(1,1),
            Name VARCHAR(MAX)
            )

            INSERT INTO @tbl(Name)
            SELECT value FROM STRING_SPLIT(@nameString, ' ');


            SELECT @firstString = Name FROM @tbl WHERE Id = 1
            SELECT @secondString = Name FROM @tbl WHERE Id = 2
            SELECT @thirdString = Name FROM @tbl WHERE Id = 3


            SELECT
            @nameString sourceString,
            CASE WHEN LEN(@firstString) > 0 THEN 'There is one space'
            ELSE 'There is not one space'
            END [Is there one space],
            CASE WHEN LEN(@secondString)> 0 THEN 'There is a second space'
            ELSE 'There is not a second space'
            END [Is there a second space],
            CASE WHEN LEN(@thirdString)> 0 THEN 'There is a third space'
            ELSE 'There is not a third space'
            END [Is there a third space]

            SELECT @nameString SourceString, @firstString [First string], @secondString [Second string] , @thirdString [Third string]

            SELECT
            CASE
            WHEN LEN(@thirdString) > 0 THEN
            @thirdString + ', ' + @firstString + ' ' + @secondString
            WHEN LEN(@secondString) > 0 AND LEN(@thirdString) = 0 THEN
            @secondString + ' ' + @thirdString + ', ' + @firstString
            WHEN LEN(@firstString) > 0 THEN
            @secondString + ', ' + @firstString
            WHEN LEN(@firstString) = 0 THEN
            @firstString
            END [Reported Name]





            share|improve this answer













            can you try this way:



            DECLARE @nameString AS VARCHAR(MAX), 
            @firstString AS VARCHAR(MAX),
            @secondString AS VARCHAR(MAX),
            @thirdString AS VARCHAR(MAX)

            SET @nameString = 'Robert Dobson, Jr.'

            DECLARE @tbl TABLE
            (
            Id INT IDENTITY(1,1),
            Name VARCHAR(MAX)
            )

            INSERT INTO @tbl(Name)
            SELECT value FROM STRING_SPLIT(@nameString, ' ');


            SELECT @firstString = Name FROM @tbl WHERE Id = 1
            SELECT @secondString = Name FROM @tbl WHERE Id = 2
            SELECT @thirdString = Name FROM @tbl WHERE Id = 3


            SELECT
            @nameString sourceString,
            CASE WHEN LEN(@firstString) > 0 THEN 'There is one space'
            ELSE 'There is not one space'
            END [Is there one space],
            CASE WHEN LEN(@secondString)> 0 THEN 'There is a second space'
            ELSE 'There is not a second space'
            END [Is there a second space],
            CASE WHEN LEN(@thirdString)> 0 THEN 'There is a third space'
            ELSE 'There is not a third space'
            END [Is there a third space]

            SELECT @nameString SourceString, @firstString [First string], @secondString [Second string] , @thirdString [Third string]

            SELECT
            CASE
            WHEN LEN(@thirdString) > 0 THEN
            @thirdString + ', ' + @firstString + ' ' + @secondString
            WHEN LEN(@secondString) > 0 AND LEN(@thirdString) = 0 THEN
            @secondString + ' ' + @thirdString + ', ' + @firstString
            WHEN LEN(@firstString) > 0 THEN
            @secondString + ', ' + @firstString
            WHEN LEN(@firstString) = 0 THEN
            @firstString
            END [Reported Name]






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 27 at 17:38









            Hasan MahmoodHasan Mahmood

            9637 silver badges10 bronze badges




            9637 silver badges10 bronze badges


























                0















                Sorry if there is some bug in the code, I don't have access to MS-SQL now I've tried to coded directly here.
                Your request is quite unusual (I agree with Robert's comment) , but a code simple like this would work.



                DECLARE @nameString as varchar(max),
                @firstString as varchar(max),
                @secondString as varchar(max),
                @thirdString as varchar(max)

                SET @nameString = 'Robert Dobson, Jr.'

                SET @thirdString = REPLACE(@nameString, ',', '')
                SET @firstString = LTRIM(SUBSTRING(@thirdString, 1, CHARINDEX(' ', @thirdString)))
                SET @thirdString = LTRIM(REPLACE(@thirdString, @firstString, ‘’))
                SET @secondString = LTRIM(SUBSTRING(@thirdString, 1, CHARINDEX(' ', @thirdString)))
                SET @thirdString = LTRIM(REPLACE(@thirdString, @secondString, ‘’))

                SELECT
                @nameString sourceString,
                @firstString [First string],
                @secondString [Second string],
                @thirdString [Third string]





                share|improve this answer





























                  0















                  Sorry if there is some bug in the code, I don't have access to MS-SQL now I've tried to coded directly here.
                  Your request is quite unusual (I agree with Robert's comment) , but a code simple like this would work.



                  DECLARE @nameString as varchar(max),
                  @firstString as varchar(max),
                  @secondString as varchar(max),
                  @thirdString as varchar(max)

                  SET @nameString = 'Robert Dobson, Jr.'

                  SET @thirdString = REPLACE(@nameString, ',', '')
                  SET @firstString = LTRIM(SUBSTRING(@thirdString, 1, CHARINDEX(' ', @thirdString)))
                  SET @thirdString = LTRIM(REPLACE(@thirdString, @firstString, ‘’))
                  SET @secondString = LTRIM(SUBSTRING(@thirdString, 1, CHARINDEX(' ', @thirdString)))
                  SET @thirdString = LTRIM(REPLACE(@thirdString, @secondString, ‘’))

                  SELECT
                  @nameString sourceString,
                  @firstString [First string],
                  @secondString [Second string],
                  @thirdString [Third string]





                  share|improve this answer



























                    0














                    0










                    0









                    Sorry if there is some bug in the code, I don't have access to MS-SQL now I've tried to coded directly here.
                    Your request is quite unusual (I agree with Robert's comment) , but a code simple like this would work.



                    DECLARE @nameString as varchar(max),
                    @firstString as varchar(max),
                    @secondString as varchar(max),
                    @thirdString as varchar(max)

                    SET @nameString = 'Robert Dobson, Jr.'

                    SET @thirdString = REPLACE(@nameString, ',', '')
                    SET @firstString = LTRIM(SUBSTRING(@thirdString, 1, CHARINDEX(' ', @thirdString)))
                    SET @thirdString = LTRIM(REPLACE(@thirdString, @firstString, ‘’))
                    SET @secondString = LTRIM(SUBSTRING(@thirdString, 1, CHARINDEX(' ', @thirdString)))
                    SET @thirdString = LTRIM(REPLACE(@thirdString, @secondString, ‘’))

                    SELECT
                    @nameString sourceString,
                    @firstString [First string],
                    @secondString [Second string],
                    @thirdString [Third string]





                    share|improve this answer













                    Sorry if there is some bug in the code, I don't have access to MS-SQL now I've tried to coded directly here.
                    Your request is quite unusual (I agree with Robert's comment) , but a code simple like this would work.



                    DECLARE @nameString as varchar(max),
                    @firstString as varchar(max),
                    @secondString as varchar(max),
                    @thirdString as varchar(max)

                    SET @nameString = 'Robert Dobson, Jr.'

                    SET @thirdString = REPLACE(@nameString, ',', '')
                    SET @firstString = LTRIM(SUBSTRING(@thirdString, 1, CHARINDEX(' ', @thirdString)))
                    SET @thirdString = LTRIM(REPLACE(@thirdString, @firstString, ‘’))
                    SET @secondString = LTRIM(SUBSTRING(@thirdString, 1, CHARINDEX(' ', @thirdString)))
                    SET @thirdString = LTRIM(REPLACE(@thirdString, @secondString, ‘’))

                    SELECT
                    @nameString sourceString,
                    @firstString [First string],
                    @secondString [Second string],
                    @thirdString [Third string]






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 27 at 18:16









                    fernolimitsfernolimits

                    12 bronze badges




                    12 bronze badges
























                        0















                        I am making the assumption that you need this to return a dynamic number of columns based on the number of spaces found in nameString. I am using a couple of things there that you will need on your system for this to work correctly.



                        First is a tally table. I keep one on my systems as a view. Here is the code that I use for this. A tally table is a great tool to help us avoid using loops. You can read more about them here.



                        create View [dbo].[cteTally] as

                        WITH
                        E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
                        E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
                        E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
                        cteTally(N) AS
                        (
                        SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                        )
                        select N from cteTally


                        The next thing we need is a string splitter. There are a number of these out there and even a built in one on recent versions of sql server. However, even the MS one misses a critical element of ordinal position for each element. Fortunately Jeff Moden has one that is set based, lightning fast and returns the position number of each element.



                        You can find the code for the DelimitedSplit8K here.



                        Now we face the challenge of returning a dynamic number of columns. For this you could use a dynamic pivot. That will work just fine. For me I find the syntax for pivot to very obtuse and prefer to use conditional aggregation, or crosstab. In this case it needs to be dynamic.



                        I created a temp table in my example to represent your table. I included some additional names to the list and some of them have more than 3 strings.



                        if OBJECT_ID('tempdb..#Something') is not null
                        drop table #Something

                        create table #Something --this represents your current table
                        (
                        nameString varchar(100)
                        )

                        insert #Something values
                        ('Robert Dobson, Jr.')
                        , ('NeoAer')
                        , ('Ryan Wilson')
                        , ('Somebody with four names')
                        , ('another with yet more names')

                        declare @StaticPortion nvarchar(2000) =
                        'with OrderedResults as
                        (
                        select nameString
                        , stringValue = replace(x.Item, '','', '''')
                        , x.ItemNumber
                        from #Something s
                        cross apply dbo.DelimitedSplit8K(s.nameString, '' '') x
                        )
                        select nameString';

                        declare @DynamicPortion nvarchar(max) = '';
                        declare @FinalStaticPortion nvarchar(2000) = ' from OrderedResults Group by nameString order by nameString';

                        select @DynamicPortion = @DynamicPortion +
                        ', MAX(Case when ItemNumber = ' + CAST(N as varchar(6)) + ' then stringValue end) as string' + CAST(N as varchar(6)) + CHAR(10)
                        from cteTally t
                        where t.N <=
                        (
                        select top 1 Count(*)
                        from #Something s
                        cross apply dbo.DelimitedSplit8K(s.nameString, ' ') x
                        group by nameString
                        order by COUNT(*) desc
                        )

                        select @StaticPortion + @DynamicPortion + @FinalStaticPortion

                        --once you are satisfied that the dynamic sql is correct uncomment the next two lines to execute it.
                        --declare @SqlToExecute nvarchar(max) = @StaticPortion + @DynamicPortion + @FinalStaticPortion;
                        --exec sp_executesql @SqlToExecute


                        If you don't this to return a dynamic number of columns we can employ a similar type of query but it far less complicated.






                        share|improve this answer





























                          0















                          I am making the assumption that you need this to return a dynamic number of columns based on the number of spaces found in nameString. I am using a couple of things there that you will need on your system for this to work correctly.



                          First is a tally table. I keep one on my systems as a view. Here is the code that I use for this. A tally table is a great tool to help us avoid using loops. You can read more about them here.



                          create View [dbo].[cteTally] as

                          WITH
                          E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
                          E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
                          E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
                          cteTally(N) AS
                          (
                          SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                          )
                          select N from cteTally


                          The next thing we need is a string splitter. There are a number of these out there and even a built in one on recent versions of sql server. However, even the MS one misses a critical element of ordinal position for each element. Fortunately Jeff Moden has one that is set based, lightning fast and returns the position number of each element.



                          You can find the code for the DelimitedSplit8K here.



                          Now we face the challenge of returning a dynamic number of columns. For this you could use a dynamic pivot. That will work just fine. For me I find the syntax for pivot to very obtuse and prefer to use conditional aggregation, or crosstab. In this case it needs to be dynamic.



                          I created a temp table in my example to represent your table. I included some additional names to the list and some of them have more than 3 strings.



                          if OBJECT_ID('tempdb..#Something') is not null
                          drop table #Something

                          create table #Something --this represents your current table
                          (
                          nameString varchar(100)
                          )

                          insert #Something values
                          ('Robert Dobson, Jr.')
                          , ('NeoAer')
                          , ('Ryan Wilson')
                          , ('Somebody with four names')
                          , ('another with yet more names')

                          declare @StaticPortion nvarchar(2000) =
                          'with OrderedResults as
                          (
                          select nameString
                          , stringValue = replace(x.Item, '','', '''')
                          , x.ItemNumber
                          from #Something s
                          cross apply dbo.DelimitedSplit8K(s.nameString, '' '') x
                          )
                          select nameString';

                          declare @DynamicPortion nvarchar(max) = '';
                          declare @FinalStaticPortion nvarchar(2000) = ' from OrderedResults Group by nameString order by nameString';

                          select @DynamicPortion = @DynamicPortion +
                          ', MAX(Case when ItemNumber = ' + CAST(N as varchar(6)) + ' then stringValue end) as string' + CAST(N as varchar(6)) + CHAR(10)
                          from cteTally t
                          where t.N <=
                          (
                          select top 1 Count(*)
                          from #Something s
                          cross apply dbo.DelimitedSplit8K(s.nameString, ' ') x
                          group by nameString
                          order by COUNT(*) desc
                          )

                          select @StaticPortion + @DynamicPortion + @FinalStaticPortion

                          --once you are satisfied that the dynamic sql is correct uncomment the next two lines to execute it.
                          --declare @SqlToExecute nvarchar(max) = @StaticPortion + @DynamicPortion + @FinalStaticPortion;
                          --exec sp_executesql @SqlToExecute


                          If you don't this to return a dynamic number of columns we can employ a similar type of query but it far less complicated.






                          share|improve this answer



























                            0














                            0










                            0









                            I am making the assumption that you need this to return a dynamic number of columns based on the number of spaces found in nameString. I am using a couple of things there that you will need on your system for this to work correctly.



                            First is a tally table. I keep one on my systems as a view. Here is the code that I use for this. A tally table is a great tool to help us avoid using loops. You can read more about them here.



                            create View [dbo].[cteTally] as

                            WITH
                            E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
                            E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
                            E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
                            cteTally(N) AS
                            (
                            SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                            )
                            select N from cteTally


                            The next thing we need is a string splitter. There are a number of these out there and even a built in one on recent versions of sql server. However, even the MS one misses a critical element of ordinal position for each element. Fortunately Jeff Moden has one that is set based, lightning fast and returns the position number of each element.



                            You can find the code for the DelimitedSplit8K here.



                            Now we face the challenge of returning a dynamic number of columns. For this you could use a dynamic pivot. That will work just fine. For me I find the syntax for pivot to very obtuse and prefer to use conditional aggregation, or crosstab. In this case it needs to be dynamic.



                            I created a temp table in my example to represent your table. I included some additional names to the list and some of them have more than 3 strings.



                            if OBJECT_ID('tempdb..#Something') is not null
                            drop table #Something

                            create table #Something --this represents your current table
                            (
                            nameString varchar(100)
                            )

                            insert #Something values
                            ('Robert Dobson, Jr.')
                            , ('NeoAer')
                            , ('Ryan Wilson')
                            , ('Somebody with four names')
                            , ('another with yet more names')

                            declare @StaticPortion nvarchar(2000) =
                            'with OrderedResults as
                            (
                            select nameString
                            , stringValue = replace(x.Item, '','', '''')
                            , x.ItemNumber
                            from #Something s
                            cross apply dbo.DelimitedSplit8K(s.nameString, '' '') x
                            )
                            select nameString';

                            declare @DynamicPortion nvarchar(max) = '';
                            declare @FinalStaticPortion nvarchar(2000) = ' from OrderedResults Group by nameString order by nameString';

                            select @DynamicPortion = @DynamicPortion +
                            ', MAX(Case when ItemNumber = ' + CAST(N as varchar(6)) + ' then stringValue end) as string' + CAST(N as varchar(6)) + CHAR(10)
                            from cteTally t
                            where t.N <=
                            (
                            select top 1 Count(*)
                            from #Something s
                            cross apply dbo.DelimitedSplit8K(s.nameString, ' ') x
                            group by nameString
                            order by COUNT(*) desc
                            )

                            select @StaticPortion + @DynamicPortion + @FinalStaticPortion

                            --once you are satisfied that the dynamic sql is correct uncomment the next two lines to execute it.
                            --declare @SqlToExecute nvarchar(max) = @StaticPortion + @DynamicPortion + @FinalStaticPortion;
                            --exec sp_executesql @SqlToExecute


                            If you don't this to return a dynamic number of columns we can employ a similar type of query but it far less complicated.






                            share|improve this answer













                            I am making the assumption that you need this to return a dynamic number of columns based on the number of spaces found in nameString. I am using a couple of things there that you will need on your system for this to work correctly.



                            First is a tally table. I keep one on my systems as a view. Here is the code that I use for this. A tally table is a great tool to help us avoid using loops. You can read more about them here.



                            create View [dbo].[cteTally] as

                            WITH
                            E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
                            E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
                            E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
                            cteTally(N) AS
                            (
                            SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                            )
                            select N from cteTally


                            The next thing we need is a string splitter. There are a number of these out there and even a built in one on recent versions of sql server. However, even the MS one misses a critical element of ordinal position for each element. Fortunately Jeff Moden has one that is set based, lightning fast and returns the position number of each element.



                            You can find the code for the DelimitedSplit8K here.



                            Now we face the challenge of returning a dynamic number of columns. For this you could use a dynamic pivot. That will work just fine. For me I find the syntax for pivot to very obtuse and prefer to use conditional aggregation, or crosstab. In this case it needs to be dynamic.



                            I created a temp table in my example to represent your table. I included some additional names to the list and some of them have more than 3 strings.



                            if OBJECT_ID('tempdb..#Something') is not null
                            drop table #Something

                            create table #Something --this represents your current table
                            (
                            nameString varchar(100)
                            )

                            insert #Something values
                            ('Robert Dobson, Jr.')
                            , ('NeoAer')
                            , ('Ryan Wilson')
                            , ('Somebody with four names')
                            , ('another with yet more names')

                            declare @StaticPortion nvarchar(2000) =
                            'with OrderedResults as
                            (
                            select nameString
                            , stringValue = replace(x.Item, '','', '''')
                            , x.ItemNumber
                            from #Something s
                            cross apply dbo.DelimitedSplit8K(s.nameString, '' '') x
                            )
                            select nameString';

                            declare @DynamicPortion nvarchar(max) = '';
                            declare @FinalStaticPortion nvarchar(2000) = ' from OrderedResults Group by nameString order by nameString';

                            select @DynamicPortion = @DynamicPortion +
                            ', MAX(Case when ItemNumber = ' + CAST(N as varchar(6)) + ' then stringValue end) as string' + CAST(N as varchar(6)) + CHAR(10)
                            from cteTally t
                            where t.N <=
                            (
                            select top 1 Count(*)
                            from #Something s
                            cross apply dbo.DelimitedSplit8K(s.nameString, ' ') x
                            group by nameString
                            order by COUNT(*) desc
                            )

                            select @StaticPortion + @DynamicPortion + @FinalStaticPortion

                            --once you are satisfied that the dynamic sql is correct uncomment the next two lines to execute it.
                            --declare @SqlToExecute nvarchar(max) = @StaticPortion + @DynamicPortion + @FinalStaticPortion;
                            --exec sp_executesql @SqlToExecute


                            If you don't this to return a dynamic number of columns we can employ a similar type of query but it far less complicated.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 27 at 18:34









                            Sean LangeSean Lange

                            27.4k2 gold badges20 silver badges35 bronze badges




                            27.4k2 gold badges20 silver badges35 bronze badges






























                                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%2f55383213%2fgrabbing-each-rows-data-and-setting-it-to-variable-tsql%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

                                Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현