This question is concerning a "large" stored procedure in SQL Server.
There is an issue with one of the SSRS reports I administer, which I have tracked down to the main stored procedure that pulls data for the report. The process the stored procedure follows is a little convoluted, but it seems to mostly work. That "mostly" is a problem, though.
We keep a JSON representation of the data behind the report in the database. The stored procedure calls a "known good" stored procedure to get the data. And then, because of the structure of the JSON, a series of CTEs parse the JSON down into a bunch of entities (questions and answers), which are then inserted into a temp table. Finally, the stored procedure uses a select statement of the form:
select ( select IsSelected
from #QuestionsAndAnswersTranspose
where QuestionKeyName = 'Foo'
and AnswerKeyName = 'Baz'
) QuestionFooBazIsSelected
, ( select AnswerText
from #QuestionsAndAnswersTranspose
where QuestionKeyName = 'Foo'
and AnswerKeyName = 'Foo Comments'
) as QuestionFooCommentsAnswerText
-- and inserts these into another temp table:
into #QuestionsAndAnswers
to turn each row in #QuestionsAndAnswersTranspose into the single field value the SSRS report cares about (for that row).
There are many, many such subqueries (approximately 500). I understand that is a lot of columns, but the documentation does say that SQL Server can handle tables with up to 1024 columns and select statements with up to 4096 columns.
Now, here is the problematic behavior this query is exhibiting. I recently got a bug report that some of the fields are coming in as null. I made a simplified version of the select statement that pulled the static JSON out of the database, parsed it with the same CTEs (which I copied into my script) and then selected the 5 specific columns (I copied and pasted the subqueries to ensure no typoes are relevant). The shortened version of the script produced the expected values, while the longer script returns null.
TL;DR: query with many subqueries is returning null values in some subqueries; simplified query with same subqueries and on same data is returning expected values.
What could be wrong here?