首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

行列拆分转换,该怎么处理

2012-01-19 
行列拆分转换表test1idtlgcltlmoneyscgclscmoney------------------------------------------------------

行列拆分转换
表test1
id                     tlgcl               tlmoney           scgcl               scmoney          
-----------   -----------   -----------   -----------   -----------  
1                       20                     200                   30                     300
2                       40                     400                   50                     500
要求写成函数;   当传入参数id=1时得到                    
name   gcl                   money              
----   -----------   -----------  
sc       30                     300
tl       20                     200
id=2时得到:
name   gcl                   money              
----   -----------   -----------  
sc       50                     500
tl       40                     400


[解决办法]
--创建测试
create table test1 (id int,tlgcl int,tlmoney int,scgcl int,scmoney int)
insert test1
select 1,20,200,30,300 union all
select 2,40,400,50,500
go

--创建内嵌表函数
create function fn_test1(@id int)
returns table
as
return
(
select name= 'tl ',gcl=tlgcl,money=tlmoney from test1 where id=@id
union all
select name= 'sc ',gcl=scgcl,money=scmoney from test1 where id=@id
)
go

--查询
select * from fn_test1(2)
select * from fn_test1(2)


--删除测试
/*
drop table test1
drop function fn_test1
*/
[解决办法]
--try

create table test1
(
id int,
tlgcl int,
tlmoney int,
scgcl int,
scmoney int
)

insert test1
select 1, 20, 200, 30, 300
union all
select 2, 40, 400, 50, 500

select * from
(
select id,gcl=tlgcl,[money]=tlmoney from test1
union all
select id,scgcl,scmoney from test1
)tmp
where id= '1 '
[解决办法]
--创建测试表
create table a (id int,tlgcl int,tlmoney int,scgcl int,scmoney int)
insert into a select 1,20,200,30,300
union all select 2,40,400,50,500

--创建测试过程
create proc caifen
@id int
as
begin
select name= 'sc ',gcl=scgcl,money=scmoney from a where id=@id
union all select name= 'tl ', gcl=tlgcl,money=tlmoney from a where id=@id


end
[解决办法]
select * from fn_test1(1)
select * from fn_test1(2)

----------------

id 通过参数传进去,还不是动态吗

如果不是,想实现什么样的动态,告知。

另:函数里不支持 EXECUTE(字串)
[解决办法]
明白了,字段动态是吧,不能用函数,只能用存储过程。
[解决办法]
还是要用 UNION ALL 的,通过 syscolumns 表,根据字段名的规则,组装动态SQL。

热点排行
Bad Request.