How can I get values from a comma separated string in SQL Server in to rows, in order to insert them into a table?
For example, with this data:
Declare @string as nvarchar(max);
Declare @substring as nvarchar(50);
set @string = "Apple, Banana, Cherry, Orange, Mango"
I have currently hard-coded set @last = 2
, for this example but @last
should contain the number of words in the string. The parameter @substring
will contain each fruit one by one in the loop, which I want to use to insert into a target table.
Here's my current code, but I'm stuck with how to set @last
to the required value:
DECLARE @first AS INT
SET @first = 1
DECLARE @step AS INT
SET @step = 1
DECLARE @last AS INT
SET @last = 2
BEGIN TRANSACTION
WHILE(@first <= @last)
BEGIN
INSERT INTO tbFruit(Name)
VALUES(@substring);
SET @first += @step
END
COMMIT TRANSACTION