Monday, December 5, 2016

Split Semicolon separated column in Sql Server (2008,2012), Versions below 2016

In case you have a column as below:
RowDataTable
Col1
1;A;2016-10-01
2;B;2016-10-02
Use code snippet below:
-- Declare the destination table;

Create table SeparatedTable ( Id int , Name nVarChar(100) , Date Date)
declare
 @c1 nVarChar(max),
 @c2 nVarChar(max),
 @c3 nVarChar(max)

DECLARE c_split CURSOR 
 FOR SELECT * FROM RowDataTable
OPEN c_split

FETCH NEXT FROM c_split into @c1
 while @@FETCH_STATUS = 0
 begin
 set @c2 = substring(@c1 ,charindex(';',@c1 )+1, len(@c1 ) )
 set @c3 = substring(@c2 ,charindex(';',@c2 )+1, len(@c2 ) )
 set @c4 = substring(@c3 ,charindex(';',@c3 )+1, len(@c3 ) )
insert into SeparatedTable
 (FILECONTENTID, NETSALARY, ACCOUNTNUMBER,)
 Values (
 subString(@c1 , 1 , charIndex(';' , @c1 )-1) ,
 subString(@c2 , 1 , charIndex(';' , @c2 )-1) ,
 subString(@c3 , 1 , charIndex(';' , @c3 )-1))
 FETCH NEXT FROM c_split into @c1
 end
close c_split
Deallocate c_split

No comments:

Post a Comment