Monday, December 15, 2014

SQL - Iterate,loop through a string

Recently I had to update a table based on a file which had some counts in it.After loading that file into a table we found that it had 25 Million plus rows in it.While we tried to run an update using the entire table we ended up getting timeouts and the table was getting locked.So we decided to do the update using smaller sets of rows.
The subset was decided on the first character of the Id column.In our case it fell into one of the following characters.

abcdefghijklmnopqrstuvwxyz0123456789

So I created a stored procedure that would take the first character of the Id column and load it into a temp table.Then I ran the update command using this subset of rows in the temp table.I repeated this for all the characters in the above string.

Below is the SQL to achieve this.

declare @id_string varchar(200)
declare @index int
declare @string_length int
declare @char char(1)

set @id_string = 'abcdefghijklmnopqrstuvwxyz0123456789'

set @index = 1
set @string_length= LEN(@id_string )

while @index<= @string_length
begin

set @char = SUBSTRING(@id_string , @index, 1)
--print @char
exec mystoredprocedure @char
set @index= @index+ 1
end

No comments: