读书人

sqlserver2005 游标解决思路

发布时间: 2012-12-19 14:13:14 作者: rapoo

sqlserver2005 游标
CityTotalSales表结构
mobile varchar(20)
CityCode varchar (10)
TotalSales int
regtotal int
region varchar (50)
数据
mobile citycode totalsales regtotal region
18316998988 BJ 387 631 E
18316998988 SH 124 631 E
18316998988 TJ 88 631 E
18316998988 NMG 32 631 E
18316998988 GZ 333 995 N
18316998988 GZ 333 995 N
13658754144 SZ 425 995 N
13658754144 HZ 123 995 N
13658754144 DG 114 995 N

请问用游标怎么把上面的数据按以下格式插入到outsms表中
sms表结构
InMobile varchar(20)
InContent1 varchar(200)


InMobile 字段保存mobile
InContent1 字段保存
InContent1 插入格式:region-regtotal citycode-totalsales
按region分组
MO-E-631 BJ-387 SH-124 TJ-88 NMG-32
MO-N-995 GZ-333 SZ-425 HZ-123 DG-114

[最优解释]

引用:
存储过程里能创建自定义函数吗?


存储过程创建自定义函数?? 没用过,调用自定义函数还是可以的。
提供一个游标小例子。

--测试数据准备
if(object_id('t1') is not null)drop table t1
CREATE table t1(
id int identity(1,1) primary key,
value nvarchar(20)
)
go
--插入测试数据
insert into t1(value)
select '值1'union all
select '值2'union all
select '值3'union all
select '值4'

--查看结果集合
--select * from t1
if(OBJECT_ID('p_print')is not null) drop procedure p_print
go
create procedure p_print
as
begin
declare @value nvarchar(20)--注意这里的变量类型应该与游标中读取出来的字段类型相同
--创建游标


declare cur1 cursor for
select value from t1
--打开游标
open cur1
fetch next from cur1 into @value--这里的@value对应游标每条记录中的字段value的值
while(@@FETCH_STATUS = 0)
begin
print 'value:'+@value
fetch next from cur1 into @value
end
--关闭游标
close cur1
--释放游标
DEALLOCATE cur1
end

--调用(去注释调用)
--exec p_print

/* 执行结果
value:值1
value:值2
value:值3
value:值4
*/


[其他解释]
why 要用游标,照我说,初学者干脆不要学游标,省得滥用
[其他解释]
InMobile 字段保存mobile
InContent1 字段保存 region-regtotal citycode-totalsales
InContent1 插入格式:
按region分组
MO-E-631 BJ-387 SH-124 TJ-88 NMG-32
MO-N-995 GZ-333 SZ-425 HZ-123 DG-114
[其他解释]
哪位大侠给个例子啊,我没写过游标
[其他解释]
存储过程里能创建自定义函数吗?

读书人网 >SQL Server

热点推荐