I have to design a report laid out in a way which differs to how the data is currently stored in the database.
There is a column in Table A, which contains the names of a number of charges, in this report I have to take each charge in this one column and place them in their own respective columns with other data. My idea was to create a temporary table (Table B) and populate the table and return it in a stored procedure like below (forgive my terrible paint skills)
I had a look on stack Overflow and tried my hand at this solution I found:
Procedure to create a table with a variable number of columns
My Code is as follows below (I haven't included the keywords like Begin/End and such)
I use the first table #tempChargeTypeTable to take note of all the charge types, which works fine.
--Declare temporary table to hold different charges in.
CREATE TABLE #tempChargeTypeTable
(
ChargeName NVARCHAR(50)
)
--Declare variable to hold value name through each loop
DECLARE @ColumnName NVARCHAR(50)
--Cursor for running through the the chargeTypeTable
DECLARE ChargeCursor CURSOR FOR SELECT ChargeName FROM #tempChargeTypeTable
--Declare variables for dynamic sql query
DECLARE @sqlQuery NVARCHAR(4000)
--Populate the temporary charge type table
INSERT INTO #tempChargeTypeTable
SELECT DISTINCT ChargeType.Name
FROM dbo.ChargeType
This below is to create the temporary table to hold all the data I need for the report, However it doesn't seem to be creating the table at all despite the code building fine with no errors
--Create a new table to hold all the information via a dynamic sql query
SET @sqlQuery = 'CREATE TABLE ##tempPaymentsAnalysisTable(MemberID NVARCHAR(50) ,FirstName NVARCHAR(50) ,
Surname NVARCHAR(50) , CategoryName NVARCHAR(50) ,'
OPEN ChargeCursor
FETCH NEXT FROM #tempChargeTypeTable INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sqlQuery = @sqlQuery + RTRIM(@ColumnName) + ' NVARCHAR(50), '
FETCH NEXT FROM ChargeCursor INTO @ColumnName
END
CLOSE ChargeCursor
DEALLOCATE ChargeCursor
SET @sqlQuery = @sqlQuery + ')'
EXEC @sqlQuery
--SELECT Statement for Test
SET @sqlQuery = 'SELECT * FROM ##tempPaymentsAnalysisTable'
Exec @sqlQuery
I've been at this for a while and I reckon I've maybe my query set wrong. Can anyone spot anything the matter?
Update: I'm using SQL Server 2012 for the database
Many thanks