Ver Mensaje Individual
  #3 (permalink)  
Antiguo 14/08/2012, 14:13
Avatar de Andres95
Andres95
Colaborador
 
Fecha de Ingreso: diciembre-2004
Mensajes: 1.802
Antigüedad: 19 años, 4 meses
Puntos: 38
Respuesta: Consulta Nombre y valor de la columna

una alternativa, procesando por conjunto, en lugar de fila por fila..

Código:
IF OBJECT_ID('tempdb..#Temporal') IS NOT NULL DROP TABLE #Temporal
GO

CREATE TABLE #Temporal (
	RowId INT IDENTITY (1, 1) Primary Key
	,MiCampo1  AS ('CAMPO01_' + CONVERT(VARCHAR, RowId) )
	,MiCampo2  AS ('CAMPO02_' + CONVERT(VARCHAR, RowId) )
)					 
GO 

INSERT INTO #Temporal DEFAULT VALUES
GO 10


SELECT RowId, TableFieldName, TableFieldValue
FROM (
SELECT * FROM #Temporal WHERE RowId >= 5
) P
UNPIVOT ( TableFieldValue 
                 FOR TableFieldName in ([MICAMPO1], [MICAMPO2]) 
               ) as unpvt		
ORDER BY RowId, TableFieldName, TableFieldValue;
GO
Resultado..

Código:
RowId       TableFieldName TableFieldValue
----------- -------------- ---------------
5           MiCampo1       CAMPO01_5
5           MiCampo2       CAMPO02_5
6           MiCampo1       CAMPO01_6
6           MiCampo2       CAMPO02_6
7           MiCampo1       CAMPO01_7
7           MiCampo2       CAMPO02_7
8           MiCampo1       CAMPO01_8
8           MiCampo2       CAMPO02_8
9           MiCampo1       CAMPO01_9
9           MiCampo2       CAMPO02_9
10          MiCampo1       CAMPO01_10
10          MiCampo2       CAMPO02_10
Igual se puede complementar con el execute_sql para hacerlo dinamico..

Saludos!
__________________
La sencillez y naturalidad son el supremo y último fin de la cultura...
--
MCTS : SQL Server 2008, .NET Framework 3.5, ASP.NET Applications.

Última edición por Andres95; 14/08/2012 a las 14:14 Razón: Lectura