Question : Split field in SQL Table into seperate rows

I have the following table, with the following fields:
tblULN
idsULNID                 chrRemark
1                             JIY LPI SUR
2                            JIY SIR
I need to split the chrRemark field into a second table (sub table).
tblULNRemarks
idsULNRemarksID     idsULNID   chrRemark
1                                  1             JIY
2                                  1             LPI
3                                  1             SUR
4                                  2             JIY
5                                  2             SIR
I can not use vba to do this, as I am dealing with several thousand records a day on slow network connection.  I need a stored procedure/T-SQL to perform this action.  The chrRemarks field can be various some ULNIDs may not have any Remarks, some have several.  The delimiter is mostly a space however a few records have a comma as a delimiter.  Unfortunatly I have no control over the information I'm fed every day I just have to make since out of it.  Thanks in advance experts.

Answer : Split field in SQL Table into seperate rows

sorry for the delay in getting back to you.... Try this out and let me know if you get any problems


IF OBJECT_ID('spr_SplitTest') IS NOT NULL
      DROP PROC spr_SplitTest
GO

CREATE PROCEDURE spr_SplitTest
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

      DECLARE @ID int
      DECLARE @Remark nvarchar(max)

      CREATE TABLE #tmp1
            (ID int, Remark nvarchar(max))

      DECLARE CUR CURSOR
      FOR SELECT idsULNID, chrRemark FROM tblULN
      OPEN CUR
      FETCH NEXT FROM CUR INTO @ID, @Remark
      WHILE @@FETCH_STATUS = 0
      BEGIN

            INSERT INTO #tmp1
                  SELECT @ID AS ID, *
                  FROM fnSplit(@Remark,' ')

            FETCH NEXT FROM CUR
            INTO @ID, @Remark
      END

      CLOSE CUR
      DEALLOCATE CUR

      SELECT * FROM #tmp1
      DROP TABLE #tmp1

END
GO

EXEC spr_SplitTest
Random Solutions  
 
programming4us programming4us