Search code examples
sqlt-sql

What is a batch?


In Transact-SQL, a batch is a set of SQL statements submitted together and executed as a group, one after the other. Batches can be stored in command files.

Is an *.sql file containing several SQL statements considered a batch? What else do we consider a batch?


Solution

  • Is an *.sql file containing several sql statements considered a batch?

    Sort of. A *.sql file is often a batch, but it could also contain several batches. You delimit separate batches via a batch separator. You might need multiple batches in a file because some statements (especially certain ALTER commands) can only be executed once per batch. This can make things like performing ALTERs in a loop tricky, because certain statement (SET) will apply through the end of a batch, and because Sql Server will have an implicit transaction which commits at the end of each batch.

    Another trick here is how you separate individual batches in a file/document. In 99% of Sql Server tools, the batch separator is "GO". However, this is something that is configurable by the tool. It's not part of the SQL language itself, and therefore you can run into the odd person now and then who uses something else, or get confused that SQL Server complains if you send it a "GO" command directly.