通过删除光标加速查询

时间:2011-04-08 08:15:36

标签: sql sql-server-2005

我的查询看起来像这样

 declare @tmpTable Table(id int)
 insert into @tmpTable(id) values (3)
 insert into @tmpTable(id) values (5)
 insert into @tmpTable(id) values (11)

 declare @tmp int
 declare @finalString varchar(MAX)

 DECLARE c1 CURSOR READ_ONLY FOR SELECT ID FROM @tmpTable
 OPEN c1
 FETCH NEXT FROM c1 INTO @tmp
 set @finalString=cast(@tmp as varchar)
 FETCH NEXT FROM c1 INTO @tmp
 WHILE @@FETCH_STATUS = 0
 begin
  set @finalString=@finalString+','+cast(@tmp as varchar)
  FETCH NEXT FROM c1 INTO @tmp
 end    
 close c1
 deallocate c1  

 select @finalString

我想从表列值创建以这种方式“3,5,11”格式化的字符串,这段代码可行,但是有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

当然 - 使用此方法(STUFF结合FOR XML PATH):

SELECT
   STUFF((SELECT ','+CAST(id AS VARCHAR(10))
          FROM @tmpTable    
          FOR XML PATH('')), 1, 1, '')

返回输出:

3,5,11

答案 1 :(得分:0)

您可以使用CTE或xquery。

CTE:
with t1(rowNum, id) as
(
    select rowNum, id from Temp1
),
t2(rowNum, str) as
(
    select 1, cast(id as varchar(250)) from t1 where rowNum=1
    union all
    select t1.rowNum, str || ',' || cast(t1.id as varchar(3)) from t1,t2
    where t2.rowNum+1 = t1.rowNum
)
select str from t2 order by rownum desc FETCH FIRST 1 ROWS ONLY;