在sql server 2000 中提供了一些聚合函數(shù),例如sum、avg、count、max和min函數(shù)。然而有時候可能要對字符串型的數(shù)據(jù)進(jìn)行拼接。例如,把學(xué)生的選課情況以逗號分割進(jìn)行顯示等等。
這種需求與sql server提供的聚合具有同一個性質(zhì),都是原本可能是多個記錄,按某一個字段經(jīng)過匯總處理后變成一條記錄。
例如學(xué)生選課的數(shù)據(jù)視圖(通常是會有學(xué)生表、課程表、學(xué)生選課表關(guān)聯(lián)而成)中的數(shù)據(jù)如下:
學(xué)號   選擇課程
050301 數(shù)據(jù)庫原理
050301 操作系統(tǒng)
050302 數(shù)據(jù)庫原理
050302 數(shù)據(jù)結(jié)構(gòu)
050303 操作系統(tǒng)
050303 數(shù)據(jù)結(jié)構(gòu)
050303 面向?qū)ο蟪绦蛟O(shè)計
而需要的數(shù)據(jù)可能是如下的結(jié)構(gòu):
學(xué)號   選擇課程
050301 數(shù)據(jù)庫原理,操作系統(tǒng)
050302 數(shù)據(jù)庫原理,數(shù)據(jù)結(jié)構(gòu)
050303 操作系統(tǒng),數(shù)據(jù)結(jié)構(gòu),面向?qū)ο蟪绦蛟O(shè)計
要實現(xiàn)這種功能,可以有兩種選擇,一種使用游標(biāo),另一種方法是使用用戶自定義函數(shù)。為了簡單,下面就創(chuàng)建一個studentcourse表,該表包括學(xué)號和選擇課程兩個字段。
使用游標(biāo)來實現(xiàn)
declare  c1  cursor for
  select studentid,coursename from studentcourse
declare @studentid  varchar(10)
declare @coursename varchar(50)
declare @count      int
if object_id('tmptable') is not null                
drop table tmptable
create table tmptable(studentid varchar(10),coursename varchar(1024)) 
open  c1
fetch next from  c1 into @studentid,@coursename
while @@fetch_status = 0
  begin
    select @count = count(*) from tmptable where [email protected]
    if @count = 0
      insert into tmptable select @studentid, @coursename     
    else
      update tmptable set coursename = coursename + ',' + @coursename where [email protected]    
    fetch next from  c1 ino @studentid,@coursename
  end
close c1
deallocate c1
select * from tmptable order by studentid 
 
使用用戶自定義函數(shù)來實現(xiàn)
create function getcourse(@studentid varchar(10))
returns varchar(4000)
as
begin
declare @s nvarchar(4000)   
  set  @s=''   
  select   @[email protected]+','+ coursename from studentcourse
    where @studentid=studentid
  set   @s=stuff(@s,1,1,'')   
  return @s 
end
go 
select distinct studentid,dbo.getcourse(studentid)     
  from      
  (   
    select  *  from  studentcourse     
  )  tmptable  
最大的網(wǎng)站源碼資源下載站,