SQL Temp Table 如何建立 Index

可在 SQL Query 建立 Temp  Table 時加入Index 讓關聯查詢效能加快

在SQL 2008R2 時尚未支援 Declare @Table Table 語法建立 Index,所以只能使用 Create Table #a 的方式來建立Temp Table 與 Index

語法如下:

 --註釋:因 CB SQL 版本較低無法使用 Declare @A Table 來建立 Index,所以只好改用 #TempTable 的方式
Create Table #a
(
	UserName	NVarchar(50) ,
	RegistrationID NVarchar(250),
	LockDateTime	DateTime Default NULL,
	CreateDateTime	DateTime Default NULL,
	UpdateDateTime	DateTime Default NULL
)
CREATE CLUSTERED INDEX tmp_Index1 ON #a(UserName)

若是在 SQL 2014 (SP2) 版本則可使用 Declare @Table Table 建立 Temp Table 外還可一併建立 Index

語法如下:

Declare @a Table
(
	UserName	NVarchar(50) INDEX tmp_Index1 (UserName),
	RegistrationID NVarchar(250),
	LockDateTime	DateTime Default NULL,
	CreateDateTime	DateTime Default NULL,
	UpdateDateTime	DateTime Default NULL
)

這樣Temp Table 在關聯其他查詢時效能可增快很多