Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are T-SQL Statement Blocks?

While researching something I can across an MSDN article which says:

Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.

The documentation didn't come close to the specific situation I was researching. After reading it I realized that I didn't understand the Return statement, and (more specifically) the definition of "statement blocks" as well as I thought. So...

What exactly is a t-sql "statement block"? Are they defined by Begin ... End like brackets in C#, { ... }, or something else entirely?

Thanks!

like image 396
John Laffoon Avatar asked Aug 31 '11 21:08

John Laffoon


People also ask

What is T-SQL block?

Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.

What are blocks in SQL?

As mentioned previously, in SQL Server, blocking occurs when one session holds a lock on a specific resource and a second SPID attempts to acquire a conflicting lock type on the same resource. Typically, the time frame for which the first SPID locks the resource is small.

What is T-SQL used for?

T-SQL or Transact SQL is the query language specific to the Microsoft SQL Server product. It can help perform operations like retrieving the data from a single row, inserting new rows, and retrieving multiple rows. It is a procedural language that is used by the SQL Server.

What is database blocking?

Blocking in SQL servers happens when a connection to SQL server blocks one or more query, and another connection to SQL server requires a conflicting lock type on query, or query locked by the primary connection. This leads to the another connection waiting until the primary connection releases its locks.


2 Answers

They come in a variety of flavors (try, catch) but generally they look like

BEGIN
    PRINT 'I am a block'
    RETURN
    PRINT 'I am still in a block but you will not see me'
END    
PRINT 'Too late, we returned from the above block'
like image 67
billinkc Avatar answered Nov 08 '22 01:11

billinkc


I would agree that that sentence in the documentation is misleading.

RETURN will not just exit the most immediate BEGIN END block (which can be nested), but will return from the entire function or procedure, and I'm not sure what it really means to exit a batch - perhaps in SSMS with the GO separator, it would continue to run later batches (I'll have to test that) - GO is a client side thing, so I'm not sure how useful that concept is in practice.

like image 43
Cade Roux Avatar answered Nov 08 '22 01:11

Cade Roux