Execute Multiple SQL Statements at Once

Problem

You want to execute more than one SQL statement without requiring multiple trips to the server.

Solution

Use a batch query, and separate your commands with a semicolon.

Discussion

Most ADO.NET providers support batch queries, which allow you to execute more than one SQL statement. To create a batch query, you simply separate the SQL statements using a semicolon, as shown here:

SELECT * FROM Products;SELECT * FROM Categories

In this example, both SQL statements are queries. If you to execute this statement using Command.ExecuteReader, you’ll first retrieve the results from the first query (the list of products). Once you have read these results, you’ll need to use the DataReader.NextResult method to move ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.