How to use stored procedures with multiple sets of data as a result
Often, when creating reports, we have to deal with databases that are far from ideal. The various "features", sometimes get us stuck. For example, how to build a report based on multiple datasets, which will result in MS SQL stored procedures? When you create a data source in the report, we can use a stored procedure in SQL query, but only for a specific table. This means that it will take only a first set of data returned by the stored procedure. To generate multiple tables of the results of a stored procedure, we need to create a data source software in the code of a custom application.
You need to create a database connection, execute the stored procedure, and enter its results into the dataset. Then we transfer dataset to the report and record the data source in the report. In this way, in the designer we will receive the prepared data source when making the report. We can go further and programmatically connect to the report source, so it's already in the data tree. But the firstly, we consider the first option with simple adding a data source to the report.
Let's say you have some WinForms applications where you generate reports. Add a button to call the report editor:
Here, we created a report object, announced the MS SQL database connection line, created a report data source, and registered it in the report. Get the GetDataSet data source as follows:
This method accepts a connection string, the name of the stored procedure and the possible parameters for the stored procedure. In our case, we did not pass anything. After you create a connection to the database stored procedure is executed. The results of her work are placed in dataAdapter.
On this stage we could have finished the article. The above code is enough to create and register a data source in a report, which will be available to you in the designer, when you edit created at the beginning of the report object.
When the Report Designer is open, you will see a blank report template. Sources of data will need to choose the settings:
However, we can improve the code and avoid further design actions in selecting data sources. That is, the report will create an additional data. To do this, we will complete the push button handler:
As you've noticed, we signed the handler to the designer's download event. Next, we include all the data sources in the report in the loop. We implement the handler for the designer's download event:
We are forwarding the pointer to an event report designer. the event handler:
Create a wizard of creating an empty report.
As a result, when editing an empty report, we get the added data: