请教一下 SQL 的语句的写法。
我有两个表
表1
CLBHCLLXCLMCCLDWCLGG ....(当然,不止这些字段
A0001双粉128金东R1194*787
A0002哑粉128金东R1194*787
A0003双粉128金东R1194*787
create table #temp1(
CLBH varchar(10),
CLLX varchar(10),
CLMC varchar(10),
CLDW varchar(10),
CLGG varchar(10)
)
insert into #temp1
select 'A0001','双粉','128金东','R','1194*787' union all
select 'A0002','哑粉','128金东','R','1194*787' union all
select 'A0003','双粉','128金东','R','1194*787'
create table #temp2(
CLBH varchar(10),
XMMC varchar(10),
FValue varchar(10)
)
insert into #temp2
select 'A0001','CLLX','' UNION ALL
select 'A0001','CLMC','' UNION ALL
select 'A0001','CLDW','' UNION ALL
select 'A0001','CLGG','' UNION ALL
select 'A0002','CLLX','' UNION ALL
select 'A0002','CLMC','' UNION ALL
select 'A0002','CLDW','' UNION ALL
select 'A0002','CLGG','' UNION ALL
select 'A0003','CLLX','' UNION ALL
select 'A0003','CLMC','' UNION ALL
select 'A0003','CLDW','' UNION ALL
select 'A0003','CLGG',''
INSERT INTO 表3 (CLBH,XMMC,FVALUE)
select CLBH,XMMC=‘CLLX’,FVALUE=CLLX
from #TEMP1
INSERT INTO 表3 (CLBH,XMMC,FVALUE)
select CLBH,XMMC=‘CLMC’,FVALUE=CLMC
from #TEMP1
......
create table temp1(
CLBH varchar(10),
CLLX varchar(10),
CLMC varchar(10),
CLDW varchar(10),
CLGG varchar(10)
)
insert into temp1
select 'A0001','双粉','128金东','R','1194*787' union all
select 'A0002','哑粉','128金东','R','1194*787' union all
select 'A0003','双粉','128金东','R','1194*787'
declare @sql varchar(max)
select @sql = isnull(@sql + ' union all ' , '' )
+ ' select CLBH , XMMC = ' + quotename(Name , '''')
+ ' , FValue = ' + quotename(Name) + ' from temp1'
from syscolumns
where name! = N'CLBH' and ID = object_id('temp1')
order by colid asc
exec(@sql + ' order by CLBH ')
/*
CLBH XMMC FValue
---------- ---- ----------
A0001 CLLX 双粉
A0001 CLMC 128金东
A0001 CLDW R
A0001 CLGG 1194*787
A0002 CLGG 1194*787
A0002 CLDW R
A0002 CLMC 128金东
A0002 CLLX 哑粉
A0003 CLLX 双粉
A0003 CLMC 128金东
A0003 CLDW R
A0003 CLGG 1194*787
*/
drop table temp1