sql - Splitting string and adding them to another table -
i using sql server management studio express. have table column names like: period, account, , forth.
the account column contains values 2abc-414-3136-12356478-000-0000-000
what need split values , add them table, e.g. 2abc goes company name, 414 goes location code, 3136 department code, 12356478 nat acc, 000 pg, 0000 ig, , 000 fut.
a detailed explanation appreciated. confused write code, please explain too.
i assume information same (7 fields example)
declare @a varchar(500) declare #crs insensitive cursor select account mysourcetable read open #crs fetch next #crs @a while(@@fetch_status = 0) begin declare @rest varchar(500) declare @field1 varchar(20) set @field1 = substring(@a, 0, charindex('-', @a)) set @rest = substring(@a, charindex('-', @a) + 1, 100) declare @field2 varchar(20) set @field2 = substring(@rest, 0, charindex('-', @rest)) set @rest = substring(@rest, charindex('-', @rest) + 1, 100) declare @field3 varchar(20) set @field3 = substring(@rest, 0, charindex('-', @rest)) set @rest = substring(@rest, charindex('-', @rest) + 1, 100) declare @field4 varchar(20) set @field4 = substring(@rest, 0, charindex('-', @rest)) set @rest = substring(@rest, charindex('-', @rest) + 1, 100) declare @field5 varchar(20) set @field5 = substring(@rest, 0, charindex('-', @rest)) set @rest = substring(@rest, charindex('-', @rest) + 1, 100) declare @field6 varchar(20) set @field6 = substring(@rest, 0, charindex('-', @rest)) set @rest = substring(@rest, charindex('-', @rest) + 1, 100) declare @field7 varchar(20) set @field7 = @rest insert mytargettable (field1, field2, field3, field4, field5, field6, field7) values (@field1, @field2, @field3, @field4, @field5, @field6, @field7) fetch next #crs @a end close #crs deallocate #crs this result can put in loop cursor scroll on rows of table result query. instead of final select can use insert statement populate destination table.
tell me if it's ok.
after edit: i've incapsulated original split cursor. cursor tool take output of query , process every rows fetch command. in case, put field account value of table in @a variable.
@@fetch_status check if exists other rows process. @ end of iteration put in target table result , go on.
this template, must customize aim, if there sintax bug please fix because i've written without real test. have nice day
Comments
Post a Comment