怎么写这个view :
把表Test:
------------------------
ID Name Value
11 测试1 4
12 大案1 3
12 大案2 8
13 看报1 5
13 看报2 6
13 看报3 3变成:
视图:viewTest:
--------------------------
ID TestInf
11 测试1(4)
12 大案1(3)||大案2(8)
13 看报1(5)||看报2(6)||看报3(3)
把表Test:
------------------------
ID Name Value
11 测试1 4
12 大案1 3
12 大案2 8
13 看报1 5
13 看报2 6
13 看报3 3变成:
视图:viewTest:
--------------------------
ID TestInf
11 测试1(4)
12 大案1(3)||大案2(8)
13 看报1(5)||看报2(6)||看报3(3)
create table Test(id int,Name varchar(20),Value int)
insert into Test select 11,'测试1',4
insert into Test select 12,'大案1',3
insert into Test select 12,'大案2',8
insert into Test select 13,'看报1',5
insert into Test select 13,'看报2',6
insert into Test select 13,'看报3',3
go--创建用户定义函数
create function f_str(@id int)
returns varchar(8000)
as
begin
declare @ret varchar(8000)
set @ret = ''
select @ret = @ret+'||'+[Name]+'('+convert(varchar(10),Value)+')' from Test where id = @id
set @ret = stuff(@ret,1,2,'')
return @ret
end
go
--执行
select id,[TestInf]=dbo.f_str(id) from Test group by id order by id
go--输出结果
--删除测试数据
drop function f_str
drop table Test
go
create table test (id int,name varchar(10),value int)
insert into test
select 11,'測試1',4
union all
select 12,'大安1',3
union all
select 12,'大安2',8
union all
select 13,'看報1',5
union all
select 13,'看報2',6
union all
select 13,'看報3',3/**/
create function f_str1(@id int)
returns varchar(1000)
as
begin
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+'||'+[name]+'('+convert(varchar,[value])+')' from test where [id]=@id
return stuff(@sql,1,2,'')
endcreate view temp_test
as
select [id],dbo.f_str1([id]) as TestInf from test group by [id]
select * from temp_test
/*The result*/
id TestInf
------- -----------------------
11 測試1(4)
12 大安1(3)||大安2(8)
13 看報1(5)||看報2(6)||看報3(3)