在查询数据库时,有时我们需要遍历每条查询结果来进行某些操作,例如拆分查询结果的字符串就要通过循环来进行,以下给出了一种循环遍历的例子供大家参考。
假设表TblTest有两个字段:id, value, 而value的值在查到后需要拆分,如:'aa,bb,cc',就可利用以下循环来进行(拆分的例子可以参考另一篇文章:Sql Server中如何拆分字符串)。
/* tmp table that store the flag to indicate if this record is processed */
declare @TblTest_tmp table(
id decimal(18,0),
[flag] int
)
/* total count for the query result */
declare @totalcount int
declare @rownum int
select @totalcount = count(1) from TblTest
set @rownum = 1
while @rownum <= @totalcount
begin
declare @id decimal(18,0),
@value varchar(2000)
select top 1 @id=[id], @value=[value] from TblTest where flag=0
/* do sth for @value, e.g. select * from split(@value, ',') */
update @TblTest_tmp set flag = 1 where [id] = @id
set @rownum = @rownum + 1
end