and then dynamic pivoting . Below code block will transform resultset in Table1 format to Table2 format.
DECLARE
@EMPLOYEE
TABLE
(DEPARTMENT
VARCHAR
(20),EMPID
INT
,ENAME
(20),SALARY
)
INSERT
SELECT
'A/C'
,01,
'TEST1'
,2000
'SALES'
,02,
'TEST2'
,3000
*
FROM
@Xmldata XML = (
FOR
XML PATH(
''
) )
--Dynamic unpivoting
INTO
##
temp
(
ROW_NUMBER()OVER(PARTITION
BY
ColumnName
ORDER
ColumnValue) rn,*
i.value(
'local-name(.)'
,
'varchar(100)'
) ColumnName,
'.'
) ColumnValue
@xmldata.nodes(
'//*[text()]'
) x(i) ) tmp ) tmp1
--SELECT * FROM ##temp
--Dynamic pivoting
@Columns NVARCHAR(
MAX
),@query NVARCHAR(
@Columns = STUFF(
', '
+QUOTENAME(
CONVERT
,rn))
DISTINCT
rn
AS
T
)),1,2,
SET
@query = N
'
SELECT ColumnName,'
+ @Columns +
SELECT * FROM ##temp
) i
PIVOT
MAX(ColumnValue) FOR rn IN ('
+ @Columns
+
')
) j ;'
;
EXEC
(@query)
--PRINT @query
DROP
Maheshkumar S Tiwari edited Revision 3. Comment: corrected typo error,corrected tags and minor edit.
Ed Price - MSFT edited Revision 2. Comment: code
Ed Price - MSFT edited Revision 1. Comment: code
Ed Price - MSFT edited Original. Comment: Tags, title, white space
Hello Ed,
Can this article be added to September T-SQL contest ? Eligible ?!!!
Sure, it can be added - strange question. The article is very nice, tricky problem. You need to add See Also section, though. Check any of my articles for example of how it should be added and formatted