Skip to main content

SQL data storing options

In SQL we have four different ways to "store" data in a table:
  • local temporary tables (#table_name),
  • global temporary tables (##table_name),
  • permanent tables (table_name),
  • table variables (@table_name).
 
Local Temporary Tables
CREATE TABLE #people
(
id INT,
name VARCHAR(25)
)
 
A temporary table is created and populated on disk, in the system database tempdb — with a session-specific identifier packed onto the name, to differentiate between similarly-named #temp tables created from other sessions. The data in this #temp table (in fact, the table itself) is visible only to the current scope (usually a stored procedure, or a set of nested stored procedures). The table gets cleared up automatically when the current procedure goes out of scope, but you should manually clean up the data when you're done with it:
 
DROP TABLE #people
 
This will be better on resources ("release early") than if you let the system clean up *after* the current session finishes the rest of its work and goes out of scope.
 
Global Temporary Tables
CREATE TABLE ##people
(
id INT,
name VARCHAR(25)
)
 
Global temporary tables operate much like local temporary tables; they are created in tempdb and cause less locking and logging than permanent tables. However, they are visible to all sessions, until the creating session goes out of scope (and the global ##temp table is no longer being referenced by other sessions).
 
Permanent Tables
CREATE TABLE people
(
id INT,
name VARCHAR(25)
)
 
A permanent table is created in the local database, however you can (unlike #temp tables) choose to create a table in another database, or even on another server, for which you have access. Like global ##temp tables, a permanent table will persist the session in which it is created, unless you also explicitly drop the table.
With a permanent table, you can deny permissions; you cannot deny users from a global ##temp table.
 
Table Variables
DECLARE @people TABLE
(
id INT,
name VARCHAR(25)
)
 
A table variable is created in memory, and so performs slightly better than #temp tables (also because there is even less locking and logging in a table variable). Table variables are automatically cleared when the procedure or function goes out of scope.
 
Table variables are the only way you can use DML statements (INSERT, UPDATE, DELETE) on temporary data within a user-defined function. You can create a table variable within a UDF, and modify the data using one of the above statements. For example, you could do this:
 
CREATE FUNCTION dbo.example1
(
)
RETURNS INT
AS
BEGIN
DECLARE @t1 TABLE (i INT)
INSERT @t1 VALUES(1)
INSERT @t1 VALUES(2)
UPDATE @t1 SET i = i + 5
DELETE @t1 WHERE i < 7
DECLARE @max INT
SELECT @max = MAX(i) FROM @t1
RETURN @max
END
GO
 
So, why not use table variables all the time?
  • You cannot use a table variable in either of the following situations:
    • INSERT @table EXEC sp_someProcedure
    • SELECT * INTO @table FROM someTable
  • You cannot truncate a table variable.
  • Table variables cannot be altered after they have been declared.
  • You cannot explicitly add an index to a table variable
  • You cannot explicitly name your constraints
  • You cannot use a user-defined function (UDF) in a CHECK CONSTRAINT, computed column, or DEFAULT CONSTRAINT.
  • You cannot use a user-defined type (UDT) in a column definition.
  • Unlike a #temp table, you cannot drop a table variable when it is no longer necessary—you just need to let it go out of scope.

Comments

Popular posts from this blog

Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098)

While accessing the active directory (AD) and authorization manager (AZMAN) , If you get “   Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098)  “ message check the    account that is being used to get the LDAP query from AD .  ERROR DETAILS Exception Details:  System.Runtime.InteropServices.COMException: Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098) Source Error: Line 154:    'Session("FullName") = System.Security.Principal.WindowsIdentity.GetCurrent.Name.ToString() Line 155: Line 156:    If Not User.IsInRole("Role1") Then Line 157:          Response.Redirect("./Login.aspx") Line 158:    End If  Stack Trace : .... SOLVE IT Steps to do check the app pool rights: Click on the website name that you are having problem with in IIS  In the right panel you will se...

Do's and Don't SQL

Do's: Writing comments whenever something is not very obvious, as it won’t impact the performance.  (--) for single line  (/*…*/) to mark a section Use proper indentation Use Upper Case for all SQL keywords. SELECT, UPDATE, INSERT, WHERE, INNER JOIN, AND, OR, LIKE. Use BEGIN... END block for multiple statements in conditional code  Use Declare and Set in beginning of Stored procedure Create objects in same database where its relevant table exists otherwise it will reduce network performance. Use PRIMARY key in WHERE condition of UPDATE or DELETE statements as this will avoid error possibilities. If User table references Employee table than the column name used in reference should be UserID where User is table name and ID primary column of User table and UserID is reference column of Employee table. Use select column name instead of select * Use CTE (Common Table Expression); its scope is limited to the next statement in SQL query, instead of...

SQL Server 2008 - Inline Variable Assignment

Microsoft SQL Server 2008 brings in a new feature of 'Declaring and Assigning' a variable all in a single line. Earlier, while using SQL 2005 and earlier versions, we had to declare a variable before assigning it. This feature is explained in detail below. In SQL 2005 and earlier versions we had to write: Declare @age int Declare @name nvarchar(25) Declare @date date Set @age = 25 Set @name = "Garry" Set @date = GETDATE() With SQL 2008 we can combine both these statements to write Declare @age int = 25 Declare @name nvarchar(25) Declare @date @date = GETDATE() Advantage : This helps us to write less code, yet get the same functionality. Even though this feature has been available it is not being used in many projects because of backward compatibility issue. If the same code is being used on both 2005 and 2008 server we would prefer writing in a format compatible to both. Do share with us :  Would you like to use this new method? If not, why?