LISTING 1: Stored Procedure to Populate the Magic Square CREATE PROC FillMagicSquare @size AS int AS DELETE MagicSquare -- Insert the first number to the middle cell in the first row INSERT INTO MagicSquare(row, col, value) VALUES(1, @size / 2 + 1, 1) -- Insert the rest of the numbers while the last number does not exist in the table WHILE NOT EXISTS (SELECT * FROM MagicSquare WHERE value = @size * @size) INSERT INTO MagicSquare(row, col, value) -- decide which coordinates to use (above / right cell or cell beneath) -- based on the NULLs returned from the ROJ SELECT CASE WHEN MS.row IS NULL THEN O1.row ELSE O2.row END AS row, CASE WHEN MS.col IS NULL THEN O1.col ELSE O2.col END AS col, O1.value FROM -- Input 1: base table MagicSquare AS MS -- Join 1: existing_cell ROJ above / right cell -- NULLs indicate cell is not occupied RIGHT OUTER JOIN -- Input 2: above / right cell info (SELECT CASE WHEN row - 1 = 0 THEN @size ELSE row - 1 END AS row, CASE WHEN col + 1 > @size THEN 1 ELSE col + 1 END AS col, value + 1 AS value FROM MagicSquare WHERE value = (SELECT MAX(value) FROM MagicSquare)) AS O1 ON MS.row = O1.row AND MS.col = O1.col -- Join 2: existing_cell ROJ above / right cell CJ cell beneath CROSS JOIN -- Input 3: cell beneath info (SELECT CASE WHEN row + 1 > @size THEN 1 ELSE row + 1 END AS row, col, value + 1 AS value FROM MagicSquare WHERE value = (SELECT MAX(value) FROM MagicSquare)) AS O2 GO