1

I have the following TSQL that I have been trying, without luck, to do 2 things with:

  1. convert Nulls to 0
  2. output to a temporary table I can use for other operations.

Part of the result is captured in the attached: enter image description here

What changes do I need to make to both capture the result into a temp table with dynamic columns, and eliminate the nulls? Thanks.

  DECLARE @cols NVARCHAR(MAX), @stmt NVARCHAR(MAX), @ParmDefinition NVARCHAR(MAX), @PVT3 NVARCHAR(MAX);

--Get distinct values of the PIVOT Column
SELECT @cols = ISNULL(@cols+', ', '')+'['+T.Cat+']'
FROM
(
    SELECT TOP 100 CONVERT( VARCHAR(2), IncomeCategoryID) AS Cat
    FROM Payroll.lu_IncomeCategory
    WHERE IsAllowance <> 0
          AND IncomeCategoryID IN
    (
        SELECT DISTINCT
               IncomeCategoryID
        FROM Payroll.Income
        WHERE IncomeCategoryID <> 0
    )
    ORDER BY IncomeCategoryID
) AS T;

SELECT @stmt = N'
    SELECT *
    FROM (SELECT EmployeeID,IncomeCategoryID, 
    SUM(RateAmount) [Amount]
FROM Payroll.Income
GROUP BY EmployeeID,  IncomeCategoryID ) as PayData
        pivot 
        (
            SUM([Amount])
            FOR IncomeCategoryID IN ('+@cols+')
        ) as IncomePivot';
EXEC sp_executesql
     @stmt = @stmt;
Slava Murygin
  • 1,951
  • 1
  • 10
  • 10
user938455
  • 89
  • 11

1 Answers1

0

Done.
For the first challenge, it worked after using the @NullToZeroCols example in one of the previous posts on this forum. For my second challenge, I eventually Selected Into a Non-Temporary table which I can search for and drop each time I execute my TSQL command. I learnt the scope of the previously created temporary table could not allow me to use it after the PIVOT command was executed.

user938455
  • 89
  • 11