国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數(shù)據(jù)庫 > SQL Server > 正文

SQL Server 開發(fā)之 數(shù)據(jù)記錄拼接聚合

2024-08-31 00:49:16
字體:
供稿:網(wǎng)友
在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)站源碼資源下載站,

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 肇庆市| 淮阳县| 法库县| 大港区| 万全县| 香河县| 电白县| 分宜县| 恩施市| 云龙县| 郑州市| 新郑市| 察隅县| 临江市| 石嘴山市| 尚志市| 长白| 乐安县| 安龙县| 行唐县| 阳东县| 涿鹿县| 津南区| 林周县| 商南县| 简阳市| 凉城县| 永胜县| 集安市| 浦北县| 淮南市| 墨江| 黄冈市| 德兴市| 阜康市| 土默特左旗| 扶风县| 阳春市| 新安县| 东山县| 海伦市|