Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a file table in sql 2012 DB which holds text file data in file_stream column.
I need to split the text in the text document to different columns in a new table.
Columns in the text file is delimitted by tabs and rows by new line character.
Please advice the suitable method.

Can we use bulk copy?

urgent please

i tried
http://www.sqlservercentral.com/Forums/Topic1476134-3077-2.aspx#bm1476786[^]

it is spliting my text file into different rows based on the delimiter new line

now each row of this result should be splitted to different columns based on tab

please help
Posted
Updated 21-Aug-13 2:16am
v2
Comments
Maciej Los 22-Aug-13 2:20am    
Do you know the number of columns? What if it will be 1K lines in a text file? Do you want to create 1K columns?
Member 10112611 22-Aug-13 2:47am    
number of col is not known in advance..but max 100 it will be

1 solution

SQL
DECLARE @NextPos INT,       @LastPos INT ,@colcount int=0,@sql varchar(1000)
    truncate table Splitresult

    SELECT  @NextPos = CHARINDEX(@Delimiter, @Text, 1),
        @LastPos = 0

    WHILE @NextPos > 0
        BEGIN
            IF exists( select  1 from Splitresult where id=@id)
            begin
                set @colcount=@colcount+1
                set @sql='update Splitresultset column'+ltrim(rtrim(str(@colcount)))+'=''' + SUBSTRING(@Text, @LastPos + 1, @NextPos - @LastPos - 1) +''' where id=' +  ltrim(rtrim(str(@id)))
                EXEC( @sql)
            end
            else
            begin
                set @colcount=@colcount+1
                set @sql='insert into Splitresult(id,column'+ltrim(rtrim(str(@colcount)))+')  select ' +  ltrim(rtrim(str(@id)))+',''' + SUBSTRING(@Text, @LastPos + 1, @NextPos - @LastPos - 1)+''''
                EXEC (@sql)
            end


            SELECT  @LastPos = @NextPos,
                @NextPos = CHARINDEX(@Delimiter, @Text, @NextPos + 1)
        END

    IF @NextPos <= @LastPos
        IF exists( select  1 from Splitresultwhere id=@id)
        begin
                set @colcount=@colcount+1
                set @sql='update Splitresultset column'+ltrim(rtrim(str(@colcount)))+'=''' + SUBSTRING(@Text, @LastPos + 1, DATALENGTH(@Text) - @LastPos) +''' where id=' +  ltrim(rtrim(str(@id)))
                EXEC( @sql)
        End
        else
        Begin
                set @colcount=@colcount+1
                set @sql='insert into Splitresult(id,column'+ltrim(rtrim(str(@colcount)))+')  select ' +  ltrim(rtrim(str(@id)))+',''' + SUBSTRING(@Text, @LastPos + 1, DATALENGTH(@Text) - @LastPos) +''''
                EXEC (@sql)
        end
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900