How do you loop a comma separated string in SQL?

While loop with comma separated values in sql server

  1. WHILE CHARINDEX(‘,’, @valueList, @pos+1)>0.
  2. set @len = CHARINDEX(‘,’, @valueList, @pos+1) – @pos.
  3. set @value = SUBSTRING(@valueList, @pos, @len)
  4. set @pos = CHARINDEX(‘,’, @valueList, @pos+@len) +1.

Can you split a string in SQL?

The STRING_SPLIT(string, separator) function in SQL Server splits the string in the first argument by the separator in the second argument. To split a sentence into words, specify the sentence as the first argument of the STRING_SPLIT() function and ‘ ‘ as the second argument.

How do you write a for loop in SQL Server?

I am detailing answer on ways to achieve different types of loops in SQL server.

  1. FOR Loop. DECLARE @cnt INT = 0; WHILE @cnt < 10 BEGIN PRINT ‘Inside FOR LOOP’; SET @cnt = @cnt + 1; END; PRINT ‘Done FOR LOOP’;
  2. DO.. WHILE Loop.
  3. REPEAT..UNTIL Loop.

How insert comma separated values in SQL query?

Insert Comma Separated (Delimited) values in a Table in SQL…

  1. The SplitString function.
  2. Using the SplitString function in SQL Query.
  3. Using the SplitString function in a Stored Procedure.
  4. Executing the Stored Procedure.

How insert comma separated values in SQL?

What is string split in SQL?

Solution. SQL Server 2016 introduced a new built-in table-valued function, STRING_SPLIT that splits the provided input string by a specified separation character and returns the output separated values in the form of table, with a row for each delimited value between each separator character.

How do I combine two columns with commas in SQL?

Try CONCAT_WS() , something like this: SELECT CONCAT_WS(‘,’, cat_id, subcat_id) FROM table… SELECT CONCAT_WS(‘,’, cat_id, subcat_id) FROM products I run the SQL but nothing happened.