CREATE PROCEDURE PascalsTriangle @Levels INT AS BEGIN SET NOCOUNT ON -- Declare variables DECLARE @counter INT = 2 DECLARE @innerCount INT DECLARE @tmp DECIMAL(38,0) DECLARE @tmp2 DECIMAL(38,0) DECLARE @dquery NVARCHAR(2048) -- Create the results table with its one column CREATE TABLE #result ( [1] DECIMAL(38,0) ) INSERT INTO #result VALUES (1) -- For every level beyond 1 WHILE(@counter <= @Levels) BEGIN -- Add another column to to the table   EXEC('ALTER TABLE #result ADD [' + @counter + '] DECIMAL(38,0)') -- Select the previous row into a temp table   SELECT *   INTO #row   FROM #result   ORDER BY 1   OFFSET (@counter - 2) ROWS   FETCH NEXT 1 ROWS ONLY -- Re-initialize the temp variables, and loop counter   SET @tmp = 1   SET @tmp2 = 1   SET @innerCount = 2 -- For every column beyond 1   WHILE(@innerCount <= @counter)   BEGIN -- Create a query which selects the current value of the cell to back it up.    SET @dquery = 'SELECT @t = [' + CAST(@innerCount AS NVARCHAR(10)) + '] FROM #row'    EXEC sp_executesql @dquery, N'@t DECIMAL(38,0) OUTPUT', @t = @tmp2 OUTPUT -- Set the value of this cell in this row to that + @tmp    EXEC('UPDATE #row SET [' + @innerCount + '] = ISNULL([' + @innerCount + '], 0) + ' + @tmp) -- Reset the temp variable    SET @tmp = @tmp2 -- Increment the count    SET @innerCount += 1   END -- Insert the row into result   INSERT INTO #result   SELECT * FROM #row -- Increment the counter   SET @counter += 1 -- Drop the row temp table   DROP TABLE #row END -- Output the result SELECT * FROM #result DROP TABLE #result END