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 see 'Basic Settings'. Click It. Select the specific pool option and enter the name of the ac

Sql Server database Read_Only / Read_Write

The ALTER DATABASE command allows a database administrator to modify SQL Server databases and their files and filegroups. This includes permitting the changing of database configuration options. Why Read Only ? When you need to ensure that the data is a database is not modified by any users or automated processes, it is useful to set the database into a read-only mode. Once read-only, the data can be read normally but any attempts to create, updated or delete table rows is disallowed. This makes the read-only mode ideal when preparing for data migration, performing data integrity checking or when the data is only required for historical reporting purposes. Make Database Read Only USE  [master] GO ALTER DATABASE  [TESTDB]  SET  READ_ONLY  WITH  NO_WAIT GO Make Database Read/Write USE  [master] GO ALTER DATABASE  [TESTDB]  SET  READ_WRITE  WITH  NO_WAIT GO In case you get the following error message make the database single user: Msg 5070, Level 16, Stat

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 temporary tables and der