使用索引是數據庫優化裏最重要的一種手段,今天通過一個簡單的例子介紹建立索引查詢的方法,希望能給剛入門的新手帶來一點幫助。關於索引的基礎知識,這裏不多做介紹,有不清楚的可以參考一下這篇文章(Sql Server數據庫中的索引)或是互聯網上的相關資料。
首先,創建一個簡單的數據庫DBTest,併爲其創建一個表IndexTest,添加幾個字段MainID(主鍵),Title,Content,CreateDate。
第二步,爲IndexTest表的Title字段創建一個索引,創建索引有兩種方式,一是通過企業管理器進行創建,二是使用查詢分析器。
1、使用企業管理器創建索引;
右鍵選中DBTest數據庫中的IndexTest表,選擇所有任務->管理索引,將會彈出一個新的對話框。
大家可以看到,Sql Server已經爲表中的主鍵創建了一個聚集索引。點擊新建,爲Title字段創建一個索引Index_Title.
2、使用查詢分析器
如果熟悉SQL語言,利用查詢分析器可以更快的創建索引,只需在查詢分析器中輸入以下代碼,點擊執行即可,得到的結果與上面的方法完全相同。
use DBTest
go
/*-- 檢測索引是否已經存在 --*/
if exists( select name from sysindexes
where name = 'Index_Title')
drop index IndexTest.Index_Title
/*-- 爲Title字段創建索引 --*/
create nonclustered index Index_Title
on IndexTest(Title)
with fillfactor = 50
go
go
/*-- 檢測索引是否已經存在 --*/
if exists( select name from sysindexes
where name = 'Index_Title')
drop index IndexTest.Index_Title
/*-- 爲Title字段創建索引 --*/
create nonclustered index Index_Title
on IndexTest(Title)
with fillfactor = 50
go
第三步,編寫測試程序,該程序使用C#進行編寫,在Visual Studio 2005中測試通過。首先新建一個Windows應用程序,在窗體中添加一個TextBox、一個RichTextBox和一個按鈕,雙擊按鈕添加事件處理程序:
string strConnection = "Server=(local);initial catalog=DBTest;user id=sa;password=sa;Connect Timeout=30";
SqlConnection conn = new SqlConnection(strConnection);
string key = this.keyWord.Text;
string cmdText = "Select * From IndexTest Where Title Like '%"+key+"%'";
SqlCommand command = new SqlCommand(cmdText,conn);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
textContext.AppendText(reader["Content"].ToString());
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
SqlConnection conn = new SqlConnection(strConnection);
string key = this.keyWord.Text;
string cmdText = "Select * From IndexTest Where Title Like '%"+key+"%'";
SqlCommand command = new SqlCommand(cmdText,conn);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
textContext.AppendText(reader["Content"].ToString());
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
一個使用索引查詢的示例就這樣完成了,是不是感覺很輕鬆?在實際的項目中,代碼不會寫得這樣簡單,但基本方法不會改變,有興趣的朋友可以參照此例爲CreateDate字段建立一個索引。如果你不嫌麻煩,可以給這個表添加上幾萬行數據(一個循環就可以搞定),然後對比一下使用索引前和使用後數據庫查詢的速度差距,加深對索引的理解。