SQL Server temporary table operations

Source: Internet
Author: User
Droptable # Tmp -- delete temporary table # Tmpcreatetable # Tmp -- create temporary table # Tmp (IDintIDENTITY () notnull, -- create column ID, each time a new record is added, 1 WokNovarchar (50), primarykey (ID) will be added -- the ID will be defined as the primary key of the temporary table # Tmp); Select * from # Tmp -- query the temporary table

Drop table # Tmp -- delete temporary table # Tmp create table # Tmp -- create temporary table # Tmp (ID int IDENTITY () not null, -- create column ID, each time a new record is added, 1 WokNo varchar (50), primary key (ID) will be added -- the ID will be defined as the temporary table # Tmp primary key ); select * from # Tmp -- Query temporary tables

Drop table # Tmp -- delete a temporary table # Tmp
Create table # Tmp -- create a temporary table # Tmp
(
ID int IDENTITY () not null, -- creates a column ID and Adds 1 to each new record.
WokNo varchar (50 ),
Primary key (ID) -- Define ID as a temporary table # primary key of Tmp
);
Select * from # Tmp -- query the data in the temporary table
Truncate table # Tmp -- clear all data and constraints of the temporary table

Example:

Declare @ Wokno Varchar (500) -- used to record employee numbers
Declare @ Str NVarchar (4000) -- used to store query statements
Declare @ Count int -- obtain the total number of records
Declare @ I int
Set @ I = 0
Select @ Count = Count (Distinct (Wokno) from # Tmp
While @ I <@ Count
Begin
Set @ Str = 'select top 1 @ Wokno = WokNo from # Tmp Where id not in (Select top '+ Str (@ I) + 'id from # Tmp )'
Exec Sp_ExecuteSql @ Str, n'@ WokNo Varchar (500) output', @ WokNo OutPut
Select @ WokNo, @ I -- display the employee ID in one row
Set @ I = @ I + 1
End


Temporary table
You can create local and global temporary tables. The local temporary table is only visible in the current session; the global temporary table is visible in all sessions.
The name of the local temporary table is preceded by a number character (# table_name), and the name of the global temporary table is preceded by two numbers (# table_name ).

The SQL statement uses the name specified for table_name In the CREATE TABLE statement to reference the temporary TABLE:

Create table # MyTempTable (cola int primary key)
Insert into # MyTempTable VALUES (1)

If a local temporary table is created by a stored procedure or an application executed by multiple users at the same time, SQL Server must be able to differentiate the tables created by different users. Therefore, SQL Server adds a digital suffix to the table name of each local temporary table internally. The full name of a temporary TABLE stored in the sysobjects table of the tempdb database is composed of the TABLE name specified in the create table statement and the digital suffix generated by the system. To allow append suffixes, the table name table_name specified for the local temporary table cannot exceed 116 characters.

Unless the drop table statement is used to explicitly remove a temporary TABLE, the system automatically removes the temporary TABLE when it exits its scope:

When the stored procedure is complete, the local temporary table created in the stored procedure is automatically removed. All nested stored procedures executed by the stored procedure of the created table can reference this table. However, the process that calls the stored procedure to create this table cannot reference this table.


All other local temporary tables are automatically removed at the end of the current session.


The global temporary table is automatically removed when the session for this table is created and other tasks are stopped to reference it. The association between tasks and tables is only maintained during the lifecycle of a single Transact-SQL statement. In other words, when the session for creating a global temporary table ends, the table is automatically removed after the last Transact-SQL statement that references the table is completed.
The local temporary table created in the stored procedure or trigger is different from the temporary table created before the stored procedure or trigger is called. If a query references a temporary table with two temporary tables with the same name at the same time, it does not define which table to resolve the query. A nested stored procedure can also create a temporary table with the same name as the temporary table created by calling its stored procedure. All references to table names in nested stored procedures are interpreted as tables created for this nested procedure. For example:

Create procedure Test2
AS
Create table # t (x int primary key)
Insert into # t VALUES (2)
SELECT Test2Col = x FROM # t
GO
Create procedure Test1
AS
Create table # t (x int primary key)
Insert into # t VALUES (1)
SELECT Test1Col = x FROM # t
EXEC Test2
GO
Create table # t (x int primary key)
Insert into # t VALUES (99)
GO
EXEC Test1
GO

The following is the result set:

(1 row (s) affected)

Test1Col
-----------
1

(1 row (s) affected)

Test2Col
-----------
2

When creating a local or global temporary TABLE, the create table syntax supports all the constraint definitions except the foreign key constraint. If the foreign key constraint is specified in the temporary table, the statement returns a warning message indicating that the constraint has been ignored and the table will still be created, but it does not have the foreign key constraint. Temporary tables cannot be referenced in the foreign key constraint.

Consider using Table variables instead of temporary tables. A temporary table is useful when you need to create an index explicitly on a temporary table or use table values for multiple stored procedures or functions. Generally, table variables provide more effective query processing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.