views:

28

answers:

1

OK the question title is vague, but here's the problem. I have a list of filenames in the first column of a table called Files that I want to parse data from that are underscore delimited, however sometimes I want to skip the underscore. Every filename is in the form of:

distance1000_7_13_2010_1_13PM_AveryDennisonAD_2300008_10S_Lock.csv

So in order to get the date and the time, I want to split this column into the following form:

Col_A = distance1000
Col_B = 7_13_2010
Col_C = 1_13PM
Col_D = AveryDennisonAD
Col_E = 2300008
Col_F = 10S
Col_G = Lock.csv

If I could truncate the .csv off of Col_G, that would be great too, although it is not necessary. Here's the code I have so far where Col_B and Col_C of dates and times are not correctly parsed:

DECLARE @RowCount INT, @I INT
SET @RowCount = (SELECT COUNT(FileName) FROM Files)
SET @I = 1

WHILE (@I <= @RowCount)
BEGIN
        DECLARE @FileName VARCHAR(1000)  
        SELECT @FileName = FileName FROM Files WHERE FileID = @I
        UPDATE Files 
        SET Col_A = dbo.fnSplit(@FileName, '_', 1),
            Col_B = dbo.fnSplit(@FileName, '_', 2), 
            Col_C = dbo.fnSplit(@FileName, '_', 3), 
            Col_D = dbo.fnSplit(@FileName, '_', 4),
            Col_E = dbo.fnSplit(@FileName, '_', 5)
            --etc.etc.
        WHERE FileID = @I
        SET @I = @I  + 1
END

How can I modify the SET statements in order to 'skip' the delimiter sometimes (and include it in the new column data) and to use the underscore delimiter to split columns at other times?

I hope this is clear. Thanks in advance!

+1  A: 

Unless I'm missing something obvious, can't you just concatenate the elements you want into the new fields?

In the example below I have also removed the loop because it doesn't appear to be necessary - however, I can't say for sure without some details of your fnSplit procedure:

UPDATE Files 
SET Col_A = dbo.fnSplit(FileName, '_', 1),
    Col_B = dbo.fnSplit(FileName, '_', 2) 
        + '_' + dbo.fnSplit(FileName, '_', 3)
        + '_' + dbo.fnSplit(FileName, '_', 4),
    Col_C = dbo.fnSplit(FileName, '_', 5), 
    Col_D = dbo.fnSplit(FileName, '_', 6),
    Col_E = dbo.fnSplit(FileName, '_', 7)
etc

(From a usability point of view, it might be better to use more meaningful names for you columns)

Ed Harper
Now why didn't I think of that earlier? Thanks Ed, that's exactly what I want! I guess I was thinking too complicated. Also, I will use different names, I guess I was just posting sample code just to be clear about what I was talking about. Thanks!
Think Blue Crew