There are two types of temporary tables in Microsoft SQL Server:
- Local - these tables visible only in the current session, and they are created like a normal table but with a # in from of the table name
- Global - these temporary tables are visible to all sessions, and they are created like a normal table but with a ## in from of the table name
- Creating temporary tables using the CREATE TABLE syntax supports constraint definitions, except for FOREIGN KEY constraints
- Temporary tables cannot be referenced in FOREIGN KEY constraints
- All local temporary temporary tables are dropped automatically at the end of the current session
- A local temporary table created in a stored procedure is dropped when the stored procedure is finished
- A local temporary table can be referenced by any nested stored procedures called by the stored procedure
- This means that if there is stored procedure "A", "B", and "C" and a temporary table is created in B, and stored procedure C is called with in B, and B is called by A, the temporary table can be referenced in both B and C, but not A.
- Local temporary table names cannot exceed 116 characters
- CREATE TABLE #TempUsers
- (
- firstName VARCHAR(30)
- , lastName VARCHAR(30)
- , nickName VARCHAR(30)
- );
As you can see, it looks almost exactly the same as creating a normal table, except for the use of the "#". And we can pretty much do everything else with the temporary table (except using foreign key constraints, of course). For example, we can insert records into it:
- INSERT INTO #TempUsers
- (
- firstName
- , lastName
- , nickName
- )
- VALUES
- (
- 'John'
- , 'Doe'
- , 'Jimmy'
- );
And if we did a select all on our table we can actually see the data entered with our insert statement:
- SELECT * FROM #TempUsers;
Output:
firstName | lastName | nickName |
John | Doe | Jimmy |
And, if you want the overly complicated MSDN description of everything there is on temporary tables in Microsoft SQL Server, click here.
No comments:
Post a Comment