sql 语句拼接 游标遍历和函数遍历

--对于表的遍历在很多时候都要用到, 下面给出了两种方法
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)--得到表的总行数
begin
insert 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 for
select code ,msg from @table;
open @curl--开启游标
fetch next from @curl into @code,@msg;
while(@@FETCH_STATUS=0)
begin
print @code;
fetch next from @curl into @code,@msg;
end 
close @curl;--关闭游标
deallocate @curl;--删除游标
--使用函数遍历
while exists(select top 1 code from @table)
begin
select top 1 @code=code,@msg=msg from @table
print @code;
delete from @table where code=@code
end
--在实际中据说函数的遍历比游标要快,而且内存占用较少.但是自己没有接触过大数据,所以在实际中怎么样也不得而知.
--在本例中 由于函数要查询和删除 游标速度较快
 
/*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)--注意一定要是nvarchar while(@i<200) begin set @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 @sql set @i=@i+1; end select * from test 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值