Procedural SQL: scope, control and cursors
Typed variables, control flow, TRY/CATCH and local SQL cursors.
Procedural batch scope
A batch defines scalar and table-variable scope. BEGIN/END structures control flow; leaf statements retain their permission checks and publication units. A local SQL cursor belongs to procedural processing; an HTTP cursor belongs to transport. These lifecycles must be managed independently.
Variables and flow control
Typed DECLARE/SET, PRINT, BEGIN/END, IF/ELSE, WHILE, BREAK, CONTINUE, RETURN and SET NOCOUNT are supported. Variables are batch-local and must be declared before use. Block nesting is limited to 100 levels. BEGIN/END is flow control, not BEGIN TRANSACTION. Every SQL leaf retains object/permission checks.
DECLARE @i INT = 0;
WHILE @i < 3
BEGIN
SET @i = @i + 1;
END;
SELECT @i AS iterations;Table variables
DECLARE @name TABLE creates a batch-local table for INSERT/SELECT/UPDATE/DELETE. It is not a #temporary table, permanent table or table-valued procedure parameter. Declare schemas/types explicitly. Do not assume table variables provide unlimited storage.
DECLARE @travail TABLE (Id INT, Libelle NVARCHAR(20));
INSERT INTO @travail VALUES (1, N'un'), (2, N'deux');
SELECT Id, Libelle FROM @travail ORDER BY Id;TRY/CATCH and SQL diagnostics
BEGIN TRY/END TRY followed by BEGIN CATCH/END CATCH and THROW are available. ERROR_NUMBER, ERROR_MESSAGE, ERROR_SEVERITY, ERROR_STATE, ERROR_LINE and ERROR_PROCEDURE expose CATCH diagnostics. THROW without arguments rethrows a caught error. Catching an error does not undo previous writes. SET NOCOUNT controls counting messages, not transactions.
BEGIN TRY
THROW 50001, N'Erreur de demonstration', 1;
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS numero, ERROR_MESSAGE() AS message;
END CATCH;Local SQL cursors versus HTTP cursors
Read-only DECLARE name CURSOR for SELECT, OPEN, FETCH INTO, CLOSE, DEALLOCATE and @@FETCH_STATUS are implemented. Options include LOCAL, FAST_FORWARD, FORWARD_ONLY, STATIC, SCROLL, INSENSITIVE and READ_ONLY, with combination validation. FAST_FORWARD cannot navigate backward; STATIC/SCROLL may do so within the implemented scope.
Procedural SQL cursors are separate from HTTP paging tokens. Forward-only HTTP results do not imply scrollable ODBC cursors. Large SQL cursors may materialize results and hit memory guards; prefer equivalent set-oriented queries.