日期:2014-05-18 浏览次数:20760 次
--不用游标 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
------解决方案--------------------
游标使用的例子,供参考:
--> 构造测试数据
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: 微波炉
**/
------解决方案--------------------
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日
*/