DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

Rollback transaction behavior on table variable

By Ashok Nalam on 24 Jul 2013 | Category: SQL Server | Tagged: tsql table transactions 
  Discuss Add Comment   |  
Add rating Rate this resource   
Table variable is a special kind of data type which stores the result set and returns data for processing. Table variable can be used in store procedures and functions. Table variables have limited scope and data will be stored in temporary storage. So they are not affected with transaction rollbacks.

In the below script we will see practically how rollback behaves for table variable.
DECLARE @student AS Table (id INT,Name VARCHAR(50) NOT NULL)
 BEGIN TRY
    BEGIN TRANSACTION       
    INSERT INTO @student Values(1,'Ram')
    INSERT INTO @student Values(2,'Rahim')
    INSERT INTO @student Values(3,NULL)
    INSERT INTO @student Values(4,'Rohan')
    COMMIT TRANSACTION
    SELECT *,Name FROM @student -- will not return data due to error at id=3
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION
    SELECT *,id FROM @student
END CATCH

Output:


In summary, we can say that Rollback Transaction does not work for table variables.

Note: Temporary tables supports Rollback Transaction. This is one of difference between Table variable and Temporary tables.

Inorder to test with Temporary tables repalce first t-sql statement with  "CREATE TABLE #student(id INT,Name VARCHAR(50) NOT NULL)" and table name as #student in above script. Output will be nothing, because Rollback Transaction supports Temporary tables.
  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9226  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.
 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys