I need to split a string by delimiters |
, then for every value obtained, I need to insert same in the name field like so:
INSERT INTO Monitoring (UserId, Name, DateCreated)
VALUES (@UserId, 'abc', getdate())
VALUES (@UserId, 'def', getdate()) etc...
Below is my code to split the string.
DECLARE @SplitStringTable TABLE (Value nvarchar(MAX) NOT NULL)
DECLARE @StringToSplit nvarchar(MAX) = 'abc|def|gh|ijj'
DECLARE @SplitEndPos int
DECLARE @SplitValue nvarchar(MAX)
DECLARE @SplitDelim nvarchar(1) = '|'
DECLARE @SplitStartPos int = 1
SET @SplitEndPos = CHARINDEX(@SplitDelim, @StringToSplit, @SplitStartPos)
WHILE @SplitEndPos > 0
BEGIN
SET @SplitValue = SUBSTRING(@StringToSplit, @SplitStartPos, (@SplitEndPos - @SplitStartPos))
INSERT @SplitStringTable (Value) VALUES (@SplitValue)
SET @SplitStartPos = @SplitEndPos + 1
SET @SplitEndPos = CHARINDEX(@SplitDelim, @StringToSplit, @SplitStartPos)
END
BEGIN TRANSACTION T1
DECLARE @i int = 0
WHILE @i < @SplitEndPos
BEGIN
INSERT INTO Monitoring (UserId, Name, DateCreated)
VALUES (@UserId, @Name, getdate())
SET @i = @i + 1
END
COMMIT TRANSACTION T1
Any help please, how shall I proceed?