#Temp tables are much like SQL tables that are defined and stored in TempDB. Difference between them and a permanent table is they are not allowed to have foreign keys.
One of the feature of temp table (#temp) is that we can add a clustered or non clustered index. Also, #temp tables allow for the auto-generated columns (fields) to be created. This can help the optimizer when determining the number of records. Below is an example of creating both a clustered and non-clustered index on a temp table.
- -- creating temp table - #employees
- CREATE TABLE #Employees
- (
- ID INT IDENTITY(1,1),
- EmployeeID INT,
- EmployeeName VARCHAR(50)
- )
- INSERT INTO #Employees
- (
- EmployeeID,
- EmployeeName
- )
- SELECT
- EmployeeID = e.EmployeeID
- ,EmployeeName = e.EmployeeName
- FROM dbo.Employees e
-
-
- CREATE CLUSTERED INDEX IDX_C_Employees_EmployeeID ON #Employees(EmployeeID)
-
-
- CREATE INDEX IDX_Users_UserName ON #Employees(EmployeeName)