Home Loop through words in a string
Reply: 2

Loop through words in a string

Philip Published in 2017-11-15 00:37:56Z

I've seen a lot of javascript stack questions around this, but nothing specifically related to SQL Server.

What I need to do is accept a string value and do a loop over the string multiple times to get back all the individual words so I can do calculations on them.

A rough idea is shown below. Anyone know how this can be achieved?

Declare @String nvarchar(50) = 'Mary had a little lamb'
Declare @word nvarchar(50) 

Start Loop 1 to 5 
    Set @word = 'Mary' (1)
    Set @word = 'had' (2)
    Set @word = 'a' (3)
    Set @word = 'little' (4)
    Set @word = 'lamb' (5)
End Loop
Philip Reply to 2017-11-15 00:47:24Z

This looks to do the job.

DECLARE @tags NVARCHAR(400) = 'mary had a little lamb'  

SELECT value  
FROM STRING_SPLIT(@tags, ' ')  
Sarhang Reply to 2017-11-15 00:54:13Z

You can split the parameter and write it in a temp table, and then use the values from the temp table. Using loops in SQL is not the best idea as they really affects your query performance.

Declare @String nvarchar(50) = 'Mary had a little lamb'

INSERT INTO #tempTable(colName)
SELECT colName
FROM dbo.Split(@String , ' ') 
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.312071 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO