日期:2014-05-18  浏览次数:20554 次

求个游标的例子!
谁给个游标的列子:
1444 1日
1472 1日
1472 2日
1716 1日
1816 1日
想要的结果是把第一列相同的第二列字符串连接在一起


本人刚接触游标,哪里有好的游标的教程能否推荐一个?

------解决方案--------------------
楼主的这个需求不需要游标,方法参考:http://blog.csdn.net/htl258/archive/2009/03/15/3993029.aspx

游标相应实例与用法参考:http://blog.csdn.net/htl258/category/582965.aspx
------解决方案--------------------
SQL code

--不用游标
create table test1
(equimentid int,errocode varchar(10))

insert into test1(equimentid,errocode) values(1,'123')
insert into test1(equimentid,errocode) values(1,'43')
insert into test1(equimentid,errocode) values(1,'567')
insert into test1(equimentid,errocode) values(2,'123')
insert into test1(equimentid,errocode) values(2,'563')
insert into test1(equimentid,errocode) values(3,'63')

create function fn_showstring(@id int)
returns varchar(100)
as
begin
  declare @sql varchar(100)
  set @sql=''
  select @sql=@sql+errocode+',' from test1 where equimentid=@id
  return @sql
end

select equimentid,dbo.fn_showstring(equimentid) errorcode from test1 group by equimentid

------解决方案--------------------
游标使用的例子,供参考:
SQL code
--> 构造测试数据
declare @tb table(pname  varchar(50))
insert @tb 
select '电视机' union all
select '电冰箱' union all
select '洗衣机' union all
select '空调' union all
select '微波炉'

--> 游标的使用
declare my_cursor cursor scroll dynamic
for
select pname from  @tb
open my_cursor
declare @pname sysname
fetch next from my_cursor into @pname
while(@@fetch_status=0)
  begin
    print 'Product Name: ' + @pname
    fetch next from my_cursor into @pname
  end
fetch first from my_cursor into @pname
close my_cursor
deallocate my_cursor

--> 结果
/**

Product Name: 电视机
Product Name: 电冰箱
Product Name: 洗衣机
Product Name: 空调
Product Name: 微波炉
**/

------解决方案--------------------
SQL code
IF OBJECT_ID('tempdb..#temp', 'u') IS NOT NULL
    DROP TABLE #temp
GO
CREATE TABLE #temp
(
    id INT,
    [date] NVARCHAR(10)
)
INSERT #temp
select '1444', N'1日' union all
select '1472', N'1日' union all
select '1472', N'2日' union all
select '1716', N'1日' union all
select '1816', N'1日'
GO
--SQL:
SELECT
    id,
    [date]=STUFF((SELECT ','+[date] FROM #temp WHERE id=t.id FOR XML PATH('')),1,1,'')
FROM #temp t
GROUP BY id
--RESULT:
/*
id    date
1444    1日
1472    1日,2日
1716    1日
1816    1日
*/