This old function I made may help as it demonstrates the concepts of looping with SQL (without a yucky cursor!).
CREATE function [dbo].[fn_Is_Uppercase]
(@string varchar(1000))
returns bit
as
begin
declare @r bit
declare @l int
declare @i int
--trim it up
set @string = mrm.dbo.trim(@string)
--need to check every character
set @l = len(@string)
set @i = 0
set @r = 1
while @i <= @l + 1 and @r = 1
begin
if ascii(substring(@string,@i - 1, 1)) <> ascii(upper(substring(@string,@i - 1, 1)))
begin
set @r = 0
end
set @i = @i + 1
end
return @r
end
This may not be the most efficient way to iterate through the characters, but it gets the job done.
I would suggest setting up a table variable with the columns you want, along with an identity (1,1) or (0,1) column to iterate through it. For each pass through the loop, write to a file in a given directory. You can check which directory/file to write to on each iteration and while properly incrementing the LCV.
Hope this helps.