Hi All,I currently have to work with a table as per below example, it has many attributes for each customer account, organised into columns for the data type:DECLARE @test TABLE(AccountID INT,DESCRIPTION NVARCHAR(50),TextValue NVARCHAR(500),NumericValue NUMERIC,Currency MONEY,DateStamp DATETIME)INSERT INTO @testSELECT 1, 'Quantity', NULL, 15, NULL, NULL UNION ALLSELECT 2, 'Telephone Order', 'Payment Declined', NULL, NULL, NULL UNION ALLSELECT 1, 'Order Total', NULL, NULL, 5689.21, NULL UNION ALLSELECT 5, 'Dispatch Date', NULL, NULL, NULL, '20120918' UNION ALLSELECT 5, 'Refund', NULL, NULL, -1500, NULL SELECT *FROM @test
I would like to pivot the data by description (in the columns) to SELECT INTO a new table, but retain the original data types in the new table.At the moment I just consolidate all data type columns into a helper column by casting all as a varchar, which I can pivot and SELECT INTO the new table. The downside is I lose the original data types, then would have to cast back which isn't very efficient with millions of rows.Any ideas appreciated.SELECT * INTO #testtablecheckFROM (SELECT AccountID, DESCRIPTION, COALESCE(CAST(TextValue AS NVARCHAR),'') + COALESCE(CAST(NumericValue AS NVARCHAR),'') + COALESCE(CAST(Currency AS NVARCHAR),'') + COALESCE(CAST(DateStamp AS NVARCHAR),'') AS HelperFROM @test) pPIVOT (MAX(Helper) FOR p.DESCRIPTIONIN ([Quantity],[Telephone Order],[Order Total],[Dispatch Date],[Refund])) AS pvtSELECT * FROM #testtablecheckSELECT COLUMN_NAME, DATA_TYPE FROM tempdb.INFORMATION_SCHEMA.COLUMNS where TABLE_NAME LIKE '%#testtablecheck%'DROP TABLE #testtablecheck