I’ve got a large T-SQL script that opens and closes a few transactions. I have read that committing a batch with a GO statement effectively clears all variables out from it’s scope.
Given the script below, will @MyImportantVariable be defined after the transaction is committed?
Is this an issue, if so, how do I overcome it?
DECLARE @MyImportantVariable INT;
SET @MyImportantVariable = 42;
DECLARE @Counter INT;
SET @Counter = 0
DECLARE UpdateGarmentCursor CURSOR FAST_FORWARD
FOR
SELECT
MyColumn
FROM
MyWonderfulTable
BEGIN TRANSACTION
WHILE @@TRAN_STATUS = 0
BEGIN
-- Do interesting work in here
SET @Counter = @Counter +1
IF(@Counter>10)
BEGIN
COMMIT TRANSACTION
-- What happens here to @MyImportantVariable?
SET @Counter = 0
BEGIN TRANSACTION
END
END
-- Close the transaction one last time
COMMIT TRANSACTION
The variable will still exist.
Your example contains no
GOcommands, only transactions.GOsignals the end of a batch… batches and transactions are two different things entirely.From MSDN: