--对于表的遍历在很多时候都要用到, 下面给出了两种方法declare @table table(code int,msg nvarchar(15));--声明表作为遍历对象declare @code varchar(15); declare @msg varchar(20);declare @i int ;set @i=1; while (@i<100000)--得到表的总行数begininsert into @table(code,msg) values(@i,'我是'+cast(@i as char(6)))set @i=@i+1;end --使用游标遍历表declare @curl cursor;set @curl =cursor forward_only static forselect code ,msg from @table;open @curl--开启游标fetch next from @curl into @code,@msg;while(@@FETCH_STATUS=0)beginPRint @code;fetch next from @curl into @code,@msg;end close @curl;--关闭游标deallocate @curl;--删除游标--使用函数遍历while exists(select top 1 code from @table)beginselect top 1 @code=code,@msg=msg from @tableprint @code;delete from @table where code=@codeend--在实际中据说函数的遍历比游标要快,而且内存占用较少.但是自己没有接触过大数据,所以在实际中怎么样也不得而知.--在本例中 由于函数要查询和删除 游标速度较快/*sql 语句拼接*/--200个0-10的随机数 拿随机数和7相处,如果余数是0 c0的值+1,最后得到200个数字出去7余数是几的和create table test (stat char(1), --在拼接的时候 对于如何使用临时表 还是不会 所以在这里创建表c0 int,c1 int,c2 int,c3 int,c4 int,c5 int,c6 int,num varchar(500));insert into test values('N',0,0,0,0,0,0,0,'');declare @i int; set @i =0; declare @remainder int ;declare @num int ; declare @sql nvarchar(100)--注意一定要是nvarcharwhile(@i<200)beginset @num=(cast ( rand ()*10 as int ));set @remainder=@num%7;set @sql=N'update test set c'+CAST(@remainder as char (1))+' =c'+CAST(@remainder as char (1))+'+1,num=num+'''+cast (@num as char(1))+''' where stat=''N''';--N'string' 表示string是个Unicode字符串print @sql;exec sp_executesql @sqlset @i=@i+1;endselect * from test
新闻热点
疑难解答