SQLTeam.com | Weblogs | Forums

Running independent SQL statements together


I have several independent chunks of SQL statements in one file. To run them, I highlight each chunk separately, run it, then copy the results and move to the next one.

I wonder if there is a way to run altogether and separate the results by a row like this:

Of course, each result will have different columns and headers but they will be separated by the above separators.

Is this possible? Or do you have any other way to run different independent statements together and produce the results in a formatted way?


If you are using SSMS - then running all of the statements in a single query window will produce the results in separate a grid for each statement.

If you want a single output - you change change the output to text mode and all output will be to a single text output window.


That's brilliant, excellent tip!

By the way, can you propose a strategy to put a title to distinguish the results from each statement?

I was thinking to add a column with the title of the statement, i.e. [Statement 1]='Statement 1' so that I can easily see which result belongs to which statement but I think it is a bit messy.

Any other idea?

Are you switching to text output - or using grid output?

For text output - add a print statement between each SQL Statement. For Grid output - put a SELECT statement between each...for example:

SELECT 'Statement 1' As Query;

{your actual query}

SELECT 'Statement 2' As Query;

{next query}

But be careful how many statements - and how much data is returned. That can and will cause issues if you return a lot of data to SSMS.

you copy them out to a csv? why not use powershell that can do all that for you?

If you are setting up a repeatable process - then Powershell is one of the many possible solutions.

That's cool, is there a good tutorial for SQL via Powershell?

Thanks but this does not work very well.

I think the best would be to append a line at the top above the headers which will have the name of the query in the first cell and the rest cells to the right will be blank.

Any idea how I can do that without breaking the actual table of the results?