我有这个问题:
Select ac.*,cp.NOMECAMPO as fieldname
FROM optes op
inner join artico art on art.id=op.IDARTICO
inner join SAM.ArtCla3ID13 ac on ac.idartico=art.id
inner join CAMPIPERS cp on cp.TABELLA = 'ArtCla3ID3'
WHERE op.id = 54782.000000
返回如下内容:
rivestimento | numtaglienti | raggio | diamscarico | fieldname |
______________________________________
nuda | 0 | 0 | 1 | diamscarico |
nuda | 0 | 0 | 1 | diamscarico |
我怎么能有这个?
diamscarico | 1
raggio | 0
numtaglienti| 0
rivestimento| nuda
谢谢!
答案 0 :(得分:2)
您可以将查询结果放入XML变量中,并在查询XML时执行取消操作。
declare @XML xml
set @XML =
(
-- Your query goes from here
select *
from YourTable
-- to here
for xml path(''), type
)
select T.X.value('local-name(.)', 'sysname') as ColumnNaame,
T.X.value('./text()[1]', 'nvarchar(max)') as Value
from @XML.nodes('*') as T(X)
答案 1 :(得分:0)
您可以使用 UNPIVOT
WITH tbl AS (
Select ac.*
FROM optes op
inner join artico art on art.id=op.IDARTICO
inner join SAM.ArtCla3ID13 ac on ac.idartico=art.id
inner join CAMPIPERS cp on cp.TABELLA = 'ArtCla3ID3'
WHERE op.id = 54782.000000
)
SELECT DISTINCT upp.column_name , upp.[value]
FROM tbl
UNPIVOT
([value] for column_name IN ([rivestimento], [numtaglienti], [raggio], [diamscarico])) upp
答案 2 :(得分:0)
它适用于静态表名,但我需要它是动态的。
这是我的代码
declare @artcla3 varchar(20)
declare @XML xml
select @artcla3='ArtCla3ID'+ convert(varchar,art.IDARTCLA3)
FROM optes op inner join artico art on art.id=op.IDARTICO
WHERE op.id = 54782.000000
exec sp_executesql N'
set @XML =
(
SELECT ac.*,cp.NOMECAMPO,cp.TITCAMPO
FROM optes op
inner join artico art on art.id=op.IDARTICO
inner join sam.'+@artcla3+' ac on ac.idartico=art.id
inner join CAMPIPERS cp on cp.TABELLA = '''+@artcla3+'''
WHERE op.id = 54782.000000
for xml path(''''), type
)
', N'@XML xml',@XML=@XML
select T.X.value('local-name(.)', 'sysname') as ColumnNaame,
T.X.value('./text()[1]', 'nvarchar(max)') as Value
from @XML.nodes('*') as T(X)