最近同事询问在Sybase中将多行结果集合并的方法,试着用cursor做了个简单的解决办法,试了下可行。(可能其中算法不够最优,提供思路而已)
因为在Sybase中无法用coalesce 一次将多行结果显示为一行 其中code结果可以以','连接
asset_status_hist 表结构如下,
[52] HGCDB1.dmo_govcorp.1> desc asset_status_hist
|Column name |Type |I|Null|Dflt|Rule|Table |Num
|--------------------|-------------|-|----|----|----|--------------------|---
|asset_id |binary(8 ) |0|No | | |asset_status_hist | 1
|asset_status_cd |char(3 ) |0|No | | |asset_status_hist | 2
|status_eff_dt |smalldatetime|0|No | | |asset_status_hist | 3
|status_end_dt |datetime |0|Yes | | |asset_status_hist | 4
(return status = 0)
可以尝试如下方法:
创建临时储存的临时表:
create table #comb (asset_id binary(8),
asset_status_cd varchar(1024))
go
-
declare cur2 cursor for select asset_id, asset_status_cd from asset_status_hist where asset_id in (0x000019000000041d,0x000019000000051c,0x000019000000061f) order by asset_id
-
-
declare @str varchar(1024)
-
declare @asset_status_cd char(3)
-
declare @oid binary(8)
-
declare @oid_now binary(8)
-
open cur2
-
fetch cur2 into @oid_now,@asset_status_cd
-
while @@fetch_status = 0
-
begin
-
-
if (@oid <> @oid_now or @oid is null)
-
begin
-
if @oid is not null
-
begin
-
insert #comb(asset_id, asset_status_cd) values( @oid, substring(@str,1,char_length(@str)-1))
-
end
-
-
set @str = null
-
set @oid = @oid_now
-
end
-
-
set @str = @str||@asset_status_cd
-
set @str = @str||','
-
-
fetch cur2 into @oid_now,@asset_status_cd
-
end
-
-
-
insert #comb(asset_id, asset_status_cd) values( @oid, substring(@str,1,char_length(@str)-1))
阅读(631) | 评论(0) | 转发(0) |