I have a table structure that contains a identifier column and a column that contains a deliminated string. What I would like to achieve is to insert the deliminated string into a new table as individual records for each of the values in the split deliminated string.
My table structure for the source table is as follows:
CREATE TABLE tablea(personID VARCHAR(8), delimStr VARCHAR(100))
Some sample data:
INSERT INTO tablea (personID, delimStr) VALUES ('A001','Monday, Tuesday')
INSERT INTO tablea (personID, delimStr) VALUES ('A002','Monday, Tuesday, Wednesday')
INSERT INTO tablea (personID, delimStr) VALUES ('A003','Monday')
My destination table is as follows:
CREATE TABLE tableb(personID VARCHAR(8), dayName VARCHAR(10))
I am attempting to create a Stored Procedure to undertake the insert, my SP so far looks like:
CREATE PROCEDURE getTKWorkingDays
@pos integer = 1
, @previous_pos integer = 0
AS
BEGIN
DECLARE @value varchar(50)
, @string varchar(100)
, @ttk varchar(8)
WHILE @pos > 0
BEGIN
SELECT @ttk = personID
, @string = delimStr
FROM dbo.tablea
SET @pos = CHARINDEX(',', @string, @previous_pos + 1)
IF @pos > 0
BEGIN
SET @value = SUBSTRING(@string, @previous_pos + 1, @pos - @previous_pos - 1)
INSERT INTO dbo.tableb ( personID, dayName ) VALUES ( @ttk, @value )
SET @previous_pos = @pos
END
END
IF @previous_pos < LEN(@string)
BEGIN
SET @value = SUBSTRING(@string, @previous_pos + 1, LEN(@string))
INSERT INTO dbo.tableb ( tkinit, dayName ) VALUES ( @ttk, @value )
END
END
The data that was inserted (only 1 records out of the 170 or so in the original table which after spliting the deliminated string should result in about 600 or so records in the new table), was incorrect.
What I am expecting to see using the sample data above is:
personID dayName
A001 Monday
A001 Tuesday
A002 Monday
A002 Tuesday
A002 Wednesday
A003 Monday
Is anyone able to point out any resources or identify where I am going wrong, and how to make this query work?
The Database is MS SQL Server 2000.
I thank you in advance for any assistance you are able to provide.
Matt
Well your
SELECTstatement which gets the “next” person doesn’t have aWHEREclause, so I’m not sure how SQL Server will know to move to the next person. If this is a one-time task, why not use a cursor?If you create a permanent numbers table (with more than 100 rows, obviously) you can use it for many purposes. You could create a split function that allows you to do the above without a cursor (well, without an explicit cursor). But this would probably work best later, when you finally get off of SQL Server 2000. Newer versions of SQL Server have much more flexible and extensible ways of performing splitting and joining.