﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>IT博客-不再回头 .net学习日记＆资料-随笔分类-SQL</title><link>http://www.cnitblog.com/sfep/category/2173.html</link><description>我再也不愿听你要求 我受够了你那些自私要求</description><language>zh-cn</language><lastBuildDate>Sun, 02 Oct 2011 21:07:45 GMT</lastBuildDate><pubDate>Sun, 02 Oct 2011 21:07:45 GMT</pubDate><ttl>60</ttl><item><title>sql 插入 图片</title><link>http://www.cnitblog.com/sfep/archive/2006/09/13/16813.html</link><dc:creator>不再回头</dc:creator><author>不再回头</author><pubDate>Wed, 13 Sep 2006 13:34:00 GMT</pubDate><guid>http://www.cnitblog.com/sfep/archive/2006/09/13/16813.html</guid><wfw:comment>http://www.cnitblog.com/sfep/comments/16813.html</wfw:comment><comments>http://www.cnitblog.com/sfep/archive/2006/09/13/16813.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.cnitblog.com/sfep/comments/commentRss/16813.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/sfep/services/trackbacks/16813.html</trackback:ping><description><![CDATA[
		<div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 98%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; BACKGROUND-COLOR: #eeeeee">
				<img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />
				<span style="COLOR: #000000">Byte[] FileByteArray </span>
				<span style="COLOR: #000000">=</span>
				<span style="COLOR: #000000"> </span>
				<span style="COLOR: #0000ff">new</span>
				<span style="COLOR: #000000"> Byte[iFileLength];<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />            Stream StreamObject </span>
				<span style="COLOR: #000000">=</span>
				<span style="COLOR: #000000"> upFile.InputStream;<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />            StreamObject.Read(FileByteArray, </span>
				<span style="COLOR: #000000">0</span>
				<span style="COLOR: #000000">, iFileLength);<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />            SqlConnection conn </span>
				<span style="COLOR: #000000">=</span>
				<span style="COLOR: #000000"> </span>
				<span style="COLOR: #0000ff">new</span>
				<span style="COLOR: #000000"> SqlConnection(</span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">server=yy;uid=sa;pwd=;database=pany</span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">);<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />            </span>
				<span style="COLOR: #0000ff">string</span>
				<span style="COLOR: #000000"> sql </span>
				<span style="COLOR: #000000">=</span>
				<span style="COLOR: #000000"> </span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">insert into t_imgs (imgData, type, description, imgSize) values </span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000"> <br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />                </span>
				<span style="COLOR: #000000">+</span>
				<span style="COLOR: #000000"> </span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">(@Image, @ContentType, @ImageDescription, @ImgSize)</span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">;<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />            SqlCommand cmd </span>
				<span style="COLOR: #000000">=</span>
				<span style="COLOR: #000000"> </span>
				<span style="COLOR: #0000ff">new</span>
				<span style="COLOR: #000000"> SqlCommand(sql, conn);<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />            cmd.Parameters.Add(</span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">@Image</span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">, SqlDbType.Binary, iFileLength).Value </span>
				<span style="COLOR: #000000">=</span>
				<span style="COLOR: #000000"> FileByteArray;<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />            cmd.Parameters.Add(</span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">@ContentType</span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">, SqlDbType.VarChar, </span>
				<span style="COLOR: #000000">50</span>
				<span style="COLOR: #000000">).Value </span>
				<span style="COLOR: #000000">=</span>
				<span style="COLOR: #000000"> upFile.ContentType;<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />            cmd.Parameters.Add(</span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">@ImageDescription</span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">, SqlDbType.VarChar, </span>
				<span style="COLOR: #000000">200</span>
				<span style="COLOR: #000000">).Value </span>
				<span style="COLOR: #000000">=</span>
				<span style="COLOR: #000000"> txtDesc.Text;<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />            cmd.Parameters.Add(</span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">@ImgSize</span>
				<span style="COLOR: #000000">"</span>
				<span style="COLOR: #000000">, SqlDbType.BigInt, </span>
				<span style="COLOR: #000000">8</span>
				<span style="COLOR: #000000">).Value </span>
				<span style="COLOR: #000000">=</span>
				<span style="COLOR: #000000"> upFile.ContentLength;<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />            conn.Open();<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />            cmd.ExecuteNonQuery();<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />            conn.Close();<br /><img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" /></span>
		</div>
<img src ="http://www.cnitblog.com/sfep/aggbug/16813.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/sfep/" target="_blank">不再回头</a> 2006-09-13 21:34 <a href="http://www.cnitblog.com/sfep/archive/2006/09/13/16813.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>access asp.net</title><link>http://www.cnitblog.com/sfep/archive/2006/08/24/15864.html</link><dc:creator>不再回头</dc:creator><author>不再回头</author><pubDate>Thu, 24 Aug 2006 05:05:00 GMT</pubDate><guid>http://www.cnitblog.com/sfep/archive/2006/08/24/15864.html</guid><wfw:comment>http://www.cnitblog.com/sfep/comments/15864.html</wfw:comment><comments>http://www.cnitblog.com/sfep/archive/2006/08/24/15864.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/sfep/comments/commentRss/15864.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/sfep/services/trackbacks/15864.html</trackback:ping><description><![CDATA[
		<p> </p>
		<div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 98%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; BACKGROUND-COLOR: #eeeeee">
				<span style="COLOR: #008080"> 1</span>
				<img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />
				<span style="COLOR: #0000ff">Dim</span>
				<span style="COLOR: #000000"> myConnection </span>
				<span style="COLOR: #0000ff">As</span>
				<span style="COLOR: #000000"> OleDbConnection <br /></span>
				<span style="COLOR: #008080"> 2</span>
				<span style="COLOR: #000000">
						<img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />    </span>
				<span style="COLOR: #0000ff">Dim</span>
				<span style="COLOR: #000000"> myCommand </span>
				<span style="COLOR: #0000ff">As</span>
				<span style="COLOR: #000000"> OleDbCommand<br /></span>
				<span style="COLOR: #008080"> 3</span>
				<span style="COLOR: #000000">
						<img id="Codehighlighter1_75_1132_Open_Image" onclick="this.style.display='none'; Codehighlighter1_75_1132_Open_Text.style.display='none'; Codehighlighter1_75_1132_Closed_Image.style.display='inline'; Codehighlighter1_75_1132_Closed_Text.style.display='inline';" src="http://www.cnitblog.com/images/OutliningIndicators/ExpandedBlockStart.gif" align="top" />
						<img id="Codehighlighter1_75_1132_Closed_Image" style="DISPLAY: none" onclick="this.style.display='none'; Codehighlighter1_75_1132_Closed_Text.style.display='none'; Codehighlighter1_75_1132_Open_Image.style.display='inline'; Codehighlighter1_75_1132_Open_Text.style.display='inline';" src="http://www.cnitblog.com/images/OutliningIndicators/ContractedBlock.gif" align="top" />    </span>
				<span id="Codehighlighter1_75_1132_Closed_Text" style="BORDER-RIGHT: #808080 1px solid; BORDER-TOP: #808080 1px solid; DISPLAY: none; BORDER-LEFT: #808080 1px solid; BORDER-BOTTOM: #808080 1px solid; BACKGROUND-COLOR: #ffffff">Sub page_load()</span>
				<span id="Codehighlighter1_75_1132_Open_Text">
						<span style="COLOR: #0000ff">sub</span>
						<span style="COLOR: #000000"> page_load(sender </span>
						<span style="COLOR: #0000ff">as</span>
						<span style="COLOR: #000000"> </span>
						<span style="COLOR: #0000ff">Object</span>
						<span style="COLOR: #000000">,e </span>
						<span style="COLOR: #0000ff">as</span>
						<span style="COLOR: #000000"> EventArgs)<br /></span>
						<span style="COLOR: #008080"> 4</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
								<br />
						</span>
						<span style="COLOR: #008080"> 5</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    </span>
						<span style="COLOR: #008000">'</span>
						<span style="COLOR: #008000">1.连接数据库</span>
						<span style="COLOR: #008000">
								<br />
						</span>
						<span style="COLOR: #008080"> 6</span>
						<span style="COLOR: #008000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
						</span>
						<span style="COLOR: #000000">    </span>
						<span style="COLOR: #0000ff">dim</span>
						<span style="COLOR: #000000"> dbname </span>
						<span style="COLOR: #0000ff">as</span>
						<span style="COLOR: #000000"> </span>
						<span style="COLOR: #0000ff">string</span>
						<span style="COLOR: #000000">
								<br />
						</span>
						<span style="COLOR: #008080"> 7</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    dbname</span>
						<span style="COLOR: #000000">=</span>
						<span style="COLOR: #000000">server.mappath(</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">authors.mdb</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">)<br /></span>
						<span style="COLOR: #008080"> 8</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    myConnection </span>
						<span style="COLOR: #000000">=</span>
						<span style="COLOR: #000000"> </span>
						<span style="COLOR: #0000ff">New</span>
						<span style="COLOR: #000000"> OleDbConnection( </span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">&amp;</span>
						<span style="COLOR: #000000">dbname )<br /></span>
						<span style="COLOR: #008080"> 9</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    myConnection.Open()<br /></span>
						<span style="COLOR: #008080">10</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    la1.text</span>
						<span style="COLOR: #000000">=</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">Connection Opened!</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">
								<br />
						</span>
						<span style="COLOR: #008080">11</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
								<br />
						</span>
						<span style="COLOR: #008080">12</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" /> <br /></span>
						<span style="COLOR: #008080">13</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
								<br />
						</span>
						<span style="COLOR: #008080">14</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    </span>
						<span style="COLOR: #008000">'</span>
						<span style="COLOR: #008000">2.添加记录</span>
						<span style="COLOR: #008000">
								<br />
						</span>
						<span style="COLOR: #008080">15</span>
						<span style="COLOR: #008000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
						</span>
						<span style="COLOR: #000000">    myCommand </span>
						<span style="COLOR: #000000">=</span>
						<span style="COLOR: #000000"> </span>
						<span style="COLOR: #0000ff">New</span>
						<span style="COLOR: #000000"> OleDbCommand( </span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">Insert INTO Authors(Authors,country) Values('Simson','usa')</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">, myConnection )<br /></span>
						<span style="COLOR: #008080">16</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    myCommand.ExecuteNonQuery()<br /></span>
						<span style="COLOR: #008080">17</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    la2.text</span>
						<span style="COLOR: #000000">=</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">New Record Inserted!</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">
								<br />
						</span>
						<span style="COLOR: #008080">18</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
								<br />
						</span>
						<span style="COLOR: #008080">19</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" /> <br /></span>
						<span style="COLOR: #008080">20</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
								<br />
						</span>
						<span style="COLOR: #008080">21</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    </span>
						<span style="COLOR: #008000">'</span>
						<span style="COLOR: #008000">3 更新数据(Access) </span>
						<span style="COLOR: #008000">
								<br />
						</span>
						<span style="COLOR: #008080">22</span>
						<span style="COLOR: #008000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
						</span>
						<span style="COLOR: #000000">    myCommand </span>
						<span style="COLOR: #000000">=</span>
						<span style="COLOR: #000000"> </span>
						<span style="COLOR: #0000ff">New</span>
						<span style="COLOR: #000000"> OleDbCommand( </span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">UPDATE Authors SET Authors='Bennett' WHERE Authors = 'Simson'</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">, myConnection )<br /></span>
						<span style="COLOR: #008080">23</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    myCommand.ExecuteNonQuery()<br /></span>
						<span style="COLOR: #008080">24</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    la3.text</span>
						<span style="COLOR: #000000">=</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">Record Updated!</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">
								<br />
						</span>
						<span style="COLOR: #008080">25</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
								<br />
						</span>
						<span style="COLOR: #008080">26</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" /> <br /></span>
						<span style="COLOR: #008080">27</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
								<br />
						</span>
						<span style="COLOR: #008080">28</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    </span>
						<span style="COLOR: #008000">'</span>
						<span style="COLOR: #008000">4 删除数据（access） </span>
						<span style="COLOR: #008000">
								<br />
						</span>
						<span style="COLOR: #008080">29</span>
						<span style="COLOR: #008000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
						</span>
						<span style="COLOR: #000000">    myCommand </span>
						<span style="COLOR: #000000">=</span>
						<span style="COLOR: #000000"> </span>
						<span style="COLOR: #0000ff">New</span>
						<span style="COLOR: #000000"> OleDbCommand( </span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">DELETE FROM Authors WHERE Authors = 'David'</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">, myConnection )<br /></span>
						<span style="COLOR: #008080">30</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    myCommand.ExecuteNonQuery()<br /></span>
						<span style="COLOR: #008080">31</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    la4.text</span>
						<span style="COLOR: #000000">=</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">Record Deleted!</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">
								<br />
						</span>
						<span style="COLOR: #008080">32</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
								<br />
						</span>
						<span style="COLOR: #008080">33</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" /> <br /></span>
						<span style="COLOR: #008080">34</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
								<br />
						</span>
						<span style="COLOR: #008080">35</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    </span>
						<span style="COLOR: #008000">'</span>
						<span style="COLOR: #008000">5 使用DateGrid显示数据 </span>
						<span style="COLOR: #008000">
								<br />
						</span>
						<span style="COLOR: #008080">36</span>
						<span style="COLOR: #008000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
						</span>
						<span style="COLOR: #000000">    myCommand </span>
						<span style="COLOR: #000000">=</span>
						<span style="COLOR: #000000"> </span>
						<span style="COLOR: #0000ff">New</span>
						<span style="COLOR: #000000"> OleDbCommand( </span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">select * FROM Authors</span>
						<span style="COLOR: #000000">"</span>
						<span style="COLOR: #000000">, myConnection )<br /></span>
						<span style="COLOR: #008080">37</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    MyDataGrid.DataSource</span>
						<span style="COLOR: #000000">=</span>
						<span style="COLOR: #000000">myCommand.Executereader()<br /></span>
						<span style="COLOR: #008080">38</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />    MyDataGrid.DataBind()<br /></span>
						<span style="COLOR: #008080">39</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
								<br />
						</span>
						<span style="COLOR: #008080">40</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" /> <br /></span>
						<span style="COLOR: #008080">41</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/InBlock.gif" align="top" />
								<br />
						</span>
						<span style="COLOR: #008080">42</span>
						<span style="COLOR: #000000">
								<img src="http://www.cnitblog.com/images/OutliningIndicators/ExpandedBlockEnd.gif" align="top" />    </span>
						<span style="COLOR: #0000ff">end sub</span>
				</span>
				<span style="COLOR: #000000"> <br /></span>
				<span style="COLOR: #008080">43</span>
				<span style="COLOR: #000000">
						<img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />
						<br />
				</span>
				<span style="COLOR: #008080">44</span>
				<span style="COLOR: #000000">
						<img src="http://www.cnitblog.com/images/OutliningIndicators/None.gif" align="top" />
				</span>
		</div>
		<p>
				<br /> </p>
<img src ="http://www.cnitblog.com/sfep/aggbug/15864.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/sfep/" target="_blank">不再回头</a> 2006-08-24 13:05 <a href="http://www.cnitblog.com/sfep/archive/2006/08/24/15864.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>sql2005分页</title><link>http://www.cnitblog.com/sfep/archive/2006/04/02/8496.html</link><dc:creator>不再回头</dc:creator><author>不再回头</author><pubDate>Sun, 02 Apr 2006 08:25:00 GMT</pubDate><guid>http://www.cnitblog.com/sfep/archive/2006/04/02/8496.html</guid><wfw:comment>http://www.cnitblog.com/sfep/comments/8496.html</wfw:comment><comments>http://www.cnitblog.com/sfep/archive/2006/04/02/8496.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/sfep/comments/commentRss/8496.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/sfep/services/trackbacks/8496.html</trackback:ping><description><![CDATA[
		<p>select * from(<br />   select *, row=row_number() over(order by 1)<br />   from 你的表<br />)a where row between (页号 -1) * 每页页数 + 1 and 页号 * 每页页数<br /><br /><br /><br />WITH PartsCTE AS(SELECT *, ROW_NUMBER() OVER(order by id DESC) as row FROM meetingroom)</p>
		<p>SELECT * from PartsCTE where row between @intStart and @intStart+@intLength-1<br /><br /><br />--SQL SERVER 2005<br />DECLARE @pagenum AS INT, @pagesize AS INT<br />SET @pagenum = 2<br />SET @pagesize = 3<br />SELECT *<br />FROM (SELECT ROW_NUMBER() OVER(ORDER BY score DESC, speaker) AS rownum, <br />        speaker, track, score<br />      FROM SpeakerStats) AS D<br />WHERE rownum BETWEEN (@pagenum-1)*@pagesize+1 AND @pagenum*@pagesize<br />ORDER BY score DESC, speaker<br /></p>
<img src ="http://www.cnitblog.com/sfep/aggbug/8496.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/sfep/" target="_blank">不再回头</a> 2006-04-02 16:25 <a href="http://www.cnitblog.com/sfep/archive/2006/04/02/8496.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>进行全文检索 </title><link>http://www.cnitblog.com/sfep/archive/2006/03/20/7826.html</link><dc:creator>不再回头</dc:creator><author>不再回头</author><pubDate>Mon, 20 Mar 2006 09:34:00 GMT</pubDate><guid>http://www.cnitblog.com/sfep/archive/2006/03/20/7826.html</guid><wfw:comment>http://www.cnitblog.com/sfep/comments/7826.html</wfw:comment><comments>http://www.cnitblog.com/sfep/archive/2006/03/20/7826.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/sfep/comments/commentRss/7826.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/sfep/services/trackbacks/7826.html</trackback:ping><description><![CDATA[
		<p class="a14">
				<b>进行全文检索</b>
		</p>
		<p class="a14">SQL Server 2000提供的全文检索语句主要有CONTAINS和FREETEXT。CONTAINS语句的功能是在表的所有列或指定列中搜索：一个字或短语；一个字或短语的前缀；与一个字相近的另一个字；一个字的派生字；一个重复出现的字。 
</p>
		<p class="a14">CONTAINS语句的语法格式为： 
</p>
		<p class="a14">CONTAINS({column | *}), &lt;contains_search 
</p>
		<p class="a14">_condition&gt;) 
</p>
		<p class="a14">其中，column是搜索列，使用“*”时说明对表中所有全文索引列进行搜索。Contains_search_ 
</p>
		<p class="a14">condition 说明CONTAINS语句的搜索内容，其语法格式为： 
</p>
		<p class="a14">{&lt;simple_term&gt;|&lt;prefix_term&gt;|&lt;proximity_term&gt;|&lt;generation_term&gt;|&lt;weighted_term&gt;}[{{AND|AND NOT|OR}&lt;contains_search_condition&gt;}] [...n] 
</p>
		<p class="a14">下面就simple_term和prefix_term参数做简要说明： 
</p>
		<p class="a14">simple_term是CONTAINS语句所搜索的单字或短语，当搜索的是一个短语时，必须使用双引号作为定界符。其格式为： 
</p>
		<p class="a14">{‘word’|“ phrase”} 
</p>
		<p class="a14">prefix_term说明CONTAINS语句所搜索的字或短语前缀，其格式为： 
</p>
		<p class="a14">{“word*” | “phrase*”} 
</p>
		<p class="a14">例如，下面语句检索Book表的Title列和Notes列中包含“database”或“computer”字符串的图书名称及其注释信息： 
</p>
		<p class="a14">select title, notes 
</p>
		<p class="a14">from book 
</p>
		<p class="a14">where contains(tilte, ‘database’) or contains(notes，‘database’) 
</p>
		<p class="a14">or contains(title，‘computer’) or contains(notes，‘computer’) 
</p>
		<p class="a14">FREETEXT语句的功能是在一个表的所有列或指定列中搜索一个自由文本格式的字符串，并返回与该字符串匹配的数据行。所以，FREETEXT语句所执行的功能又称做自由式全文查询。 
</p>
		<p class="a14">FREETEXT语句的语法格式为：FREETEXT({column | * }，‘freetext_string’) 
</p>
		<p class="a14">其中，column是被搜索列，使用“*”时说明对表中的所有全文索引列进行搜索。Freetext_string参数指出所搜索的自由文本格式字符串。 
</p>
		<p class="a14">例如，下面语句使用FREETEXT语句搜索Book表中包含“Successful Life”字符串的数据行： 
</p>
		<p class="a14">select title, notes 
</p>
		<p class="a14">from book 
</p>
		<p class="a14">where freetext(*，‘Successful Life’) </p>
<img src ="http://www.cnitblog.com/sfep/aggbug/7826.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/sfep/" target="_blank">不再回头</a> 2006-03-20 17:34 <a href="http://www.cnitblog.com/sfep/archive/2006/03/20/7826.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>海量数据库的查询优化及分页算法方案 </title><link>http://www.cnitblog.com/sfep/archive/2006/03/20/7825.html</link><dc:creator>不再回头</dc:creator><author>不再回头</author><pubDate>Mon, 20 Mar 2006 09:33:00 GMT</pubDate><guid>http://www.cnitblog.com/sfep/archive/2006/03/20/7825.html</guid><wfw:comment>http://www.cnitblog.com/sfep/comments/7825.html</wfw:comment><comments>http://www.cnitblog.com/sfep/archive/2006/03/20/7825.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/sfep/comments/commentRss/7825.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/sfep/services/trackbacks/7825.html</trackback:ping><description><![CDATA[
		<div>CREATE TABLE [dbo].[TGongwen] (<span>    --TGongwen</span>是红头文件表名</div>
		<div>
				<span>   [Gid] [int] IDENTITY (1, 1) NOT NULL ,<br />--</span>本表的<span>id号，也是主键</span></div>
		<div>
				<span>   [title] [varchar] (80) COLLATE Chinese_PRC_CI_AS NULL , <br />--</span>红头文件的标题</div>
		<div>
				<span>   [fariqi] [datetime] NULL ,<br />--</span>发布日期</div>
		<div>
				<span>   [neibuYonghu] [varchar] (70) COLLATE Chinese_PRC_CI_AS NULL ,<br />--</span>发布用户</div>
		<div>
				<span>   [reader] [varchar] (900) COLLATE Chinese_PRC_CI_AS NULL ,</span>
		</div>
		<div>--需要浏览的用户。每个用户中间用分隔符“<span>,”分开</span></div>
		<div>) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]</div>
		<div>GO</div>
		<div> </div>
		<div>下面，我们来往数据库中添加<span>1000万条数据：</span></div>
		<div>declare @i int</div>
		<div>set @i=1</div>
		<div>while @i&lt;=250000</div>
		<div>begin</div>
		<div>
				<span>    insert into Tgongwen(fariqi,neibuyonghu,reader,title) values('2004-2-5','</span>通信科<span>','通信科,办公室,王局长,刘局长,张局长,admin,刑侦支队,特勤支队,交巡警支队,经侦支队,户政科,治安支队,外事科','这是最先的25万条记录')</span></div>
		<div>
				<span>    set @i=@i+1</span>
		</div>
		<div>end</div>
		<div>GO</div>
		<div> </div>
		<div>declare @i int</div>
		<div>set @i=1</div>
		<div>while @i&lt;=250000</div>
		<div>begin</div>
		<div>
				<span>    insert into Tgongwen(fariqi,neibuyonghu,reader,title) values('2004-9-16','</span>办公室<span>','办公室,通信科,王局长,刘局长,张局长,admin,刑侦支队,特勤支队,交巡警支队,经侦支队,户政科,外事科','这是中间的25万条记录')</span></div>
		<div>
				<span>    set @i=@i+1</span>
		</div>
		<div>end</div>
		<div>GO</div>
		<div> </div>
		<div>declare @h int</div>
		<div>set @h=1</div>
		<div>while @h&lt;=100</div>
		<div>begin</div>
		<div>declare @i int</div>
		<div>set @i=2002</div>
		<div>while @i&lt;=2003</div>
		<div>begin</div>
		<div>declare @j int</div>
		<div>
				<span>        set @j=0</span>
		</div>
		<div>
				<span>        while @j&lt;50</span>
		</div>
		<div>
				<span>            begin</span>
		</div>
		<div>declare @k int</div>
		<div>
				<span>            set @k=0</span>
		</div>
		<div>
				<span>            while @k&lt;50</span>
		</div>
		<div>
				<span>            begin</span>
		</div>
		<div>
				<span>    insert into Tgongwen(fariqi,neibuyonghu,reader,title) values(cast(@i as varchar(4))+'-8-15 3:'+cast(@j as varchar(2))+':'+cast(@j as varchar(2)),'</span>通信科<span>','办公室,通信科,王局长,刘局长,张局长,admin,刑侦支队,特勤支队,交巡警支队,经侦支队,户政科,外事科','这是最后的50万条记录')</span></div>
		<div>
				<span>            set @k=@k+1</span>
		</div>
		<div>
				<span>            end</span>
		</div>
		<div>set @j=@j+1</div>
		<div>
				<span>        end</span>
		</div>
		<div>set @i=@i+1</div>
		<div>end</div>
		<div>set @h=@h+1</div>
		<div>end</div>
		<div>GO</div>
		<div> </div>
		<div>declare @i int</div>
		<div>set @i=1</div>
		<div>while @i&lt;=9000000</div>
		<div>begin</div>
		<div>
				<span>    insert into Tgongwen(fariqi,neibuyonghu,reader,title) values('2004-5-5','</span>通信科<span>','通信科,办公室,王局长,刘局长,张局长,admin,刑侦支队,特勤支队,交巡警支队,经侦支队,户政科,治安支队,外事科','这是最后添加的900万条记录')</span></div>
		<div>
				<span>    set @i=@i+1000000</span>
		</div>
		<div>end</div>
		<div>
				<div>GO</div>
		</div>
		<div>通过以上语句，我们创建了<span>25万条由通信科于2004年2月5日发布的记录，25万条由办公室于2004年9月6日发布的记录，2002年和2003年各100个2500条相同日期、不同分秒的由通信科发布的记录（共50万条），还有由通信科于2004年5月5日发布的900万条记录，合计1000万条。</span></div>
		<div> </div>
		<div>一、因情制宜，建立“适当”的索引</div>
		<div>建立“适当”的索引是实现查询优化的首要前提。</div>
		<div>索引（<span>index）是除表之外另一重要的、用户定义的存储在物理介质上的数据结构。当根据索引码的值搜索数据时，索引提供了对数据的快速访问。事实上，没有索引,数据库也能根据SELECT语句成功地检索到结果，但随着表变得越来越大，使用“适当”的索引的效果就越来越明显。注意，在这句话中，我们用了“适当”这个词，这是因为，如果使用索引时不认真考虑其实现过程，索引既可以提高也会破坏数据库的工作性能。</span></div>
		<div>
				<b>（一）深入浅出理解索引结构</b>
		</div>
		<div>实际上，您可以把索引理解为一种特殊的目录。微软的<span>SQL SERVER提供了两种索引：聚集索引（clustered index，也称聚类索引、簇集索引）和非聚集索引（nonclustered index，也称非聚类索引、非簇集索引）。下面，我们举例来说明一下聚集索引和非聚集索引的区别：</span></div>
		<div>其实，我们的汉语字典的正文本身就是一个聚集索引。比如，我们要查“安”字，就会很自然地翻开字典的前几页，因为“安”的拼音是“<span>an”，而按照拼音排序汉字的字典是以英文字母“a”开头并以“z”结尾的，那么“安”字就自然地排在字典的前部。如果您翻完了所有以“a”开头的部分仍然找不到这个字，那么就说明您的字典中没有这个字；同样的，如果查“张”字，那您也会将您的字典翻到最后部分，因为“张”的拼音是“zhang”。也就是说，字典的正文部分本身就是一个目录，您不需要再去查其他目录来找到您需要找的内容。</span></div>
		<div>我们把这种正文内容本身就是一种按照一定规则排列的目录称为“聚集索引”。</div>
		<div>如果您认识某个字，您可以快速地从自动中查到这个字。但您也可能会遇到您不认识的字，不知道它的发音，这时候，您就不能按照刚才的方法找到您要查的字，而需要去根据“偏旁部首”查到您要找的字，然后根据这个字后的页码直接翻到某页来找到您要找的字。但您结合“部首目录”和“检字表”而查到的字的排序并不是真正的正文的排序方法，比如您查“张”字，我们可以看到在查部首之后的检字表中“张”的页码是<span>672页，检字表中“张”的上面是“驰”字，但页码却是63页，“张”的下面是“弩”字，页面是390页。很显然，这些字并不是真正的分别位于“张”字的上下方，现在您看到的连续的“驰、张、弩”三字实际上就是他们在非聚集索引中的排序，是字典正文中的字在非聚集索引中的映射。我们可以通过这种方式来找到您所需要的字，但它需要两个过程，先找到目录中的结果，然后再翻到您所需要的页码。</span></div>
		<div>我们把这种目录纯粹是目录，正文纯粹是正文的排序方式称为“非聚集索引”。</div>
		<div>通过以上例子，我们可以理解到什么是“聚集索引”和“非聚集索引”。</div>
		<div>进一步引申一下，我们可以很容易的理解：每个表只能有一个聚集索引，因为目录只能按照一种方法进行排序。</div>
		<div>
				<b>（二）何时使用聚集索引或非聚集索引</b>
		</div>
		<div>下面的表总结了何时使用聚集索引或非聚集索引（<b>很重要</b>）。</div>
		<p>
		</p>
		<table cellspacing="0" cellpadding="0" border="1">
				<tbody>
						<tr>
								<td valign="top" width="189">
										<div align="center">
												<b>动作描述</b>
										</div>
								</td>
								<td valign="top" width="189">
										<div align="center">
												<b>使用聚集索引</b>
										</div>
								</td>
								<td valign="top" width="189">
										<div align="center">
												<b>使用非聚集索引</b>
										</div>
								</td>
						</tr>
						<tr>
								<td width="189">
										<div align="center">列经常被分组排序</div>
								</td>
								<td width="189">
										<div align="center">应</div>
								</td>
								<td width="189">
										<div align="center">应</div>
								</td>
						</tr>
						<tr>
								<td width="189">
										<div align="center">返回某范围内的数据</div>
								</td>
								<td width="189">
										<div align="center">应</div>
								</td>
								<td width="189">
										<div align="center">不应</div>
								</td>
						</tr>
						<tr>
								<td width="189">
										<div align="center">一个或极少不同值</div>
								</td>
								<td width="189">
										<div align="center">不应</div>
								</td>
								<td width="189">
										<div align="center">不应</div>
								</td>
						</tr>
						<tr>
								<td width="189">
										<div align="center">小数目的不同值</div>
								</td>
								<td width="189">
										<div align="center">应</div>
								</td>
								<td width="189">
										<div align="center">不应</div>
								</td>
						</tr>
						<tr>
								<td width="189">
										<div align="center">大数目的不同值</div>
								</td>
								<td width="189">
										<div align="center">不应</div>
								</td>
								<td width="189">
										<div align="center">应</div>
								</td>
						</tr>
						<tr>
								<td width="189">
										<div align="center">频繁更新的列</div>
								</td>
								<td width="189">
										<div align="center">不应</div>
								</td>
								<td width="189">
										<div align="center">应</div>
								</td>
						</tr>
						<tr>
								<td width="189">
										<div align="center">外键列</div>
								</td>
								<td width="189">
										<div align="center">应</div>
								</td>
								<td width="189">
										<div align="center">应</div>
								</td>
						</tr>
						<tr>
								<td width="189">
										<div align="center">主键列</div>
								</td>
								<td width="189">
										<div align="center">应</div>
								</td>
								<td width="189">
										<div align="center">应</div>
								</td>
						</tr>
						<tr>
								<td width="189">
										<div align="center">频繁修改索引列</div>
								</td>
								<td width="189">
										<div align="center">不应</div>
								</td>
								<td width="189">
										<div align="center">应</div>
								</td>
						</tr>
				</tbody>
		</table>
		<div>事实上，我们可以通过前面聚集索引和非聚集索引的定义的例子来理解上表。如：返回某范围内的数据一项。比如您的某个表有一个时间列，恰好您把聚合索引建立在了该列，这时您查询<span>2004年1月1日至2004年10月1日之间的全部数据时，这个速度就将是很快的，因为您的这本字典正文是按日期进行排序的，聚类索引只需要找到要检索的所有数据中的开头和结尾数据即可；而不像非聚集索引，必须先查到目录中查到每一项数据对应的页码，然后再根据页码查到具体内容。</span></div>
		<div>
				<b>（三）结合实际，谈索引使用的误区</b>
		</div>
		<div>理论的目的是应用。虽然我们刚才列出了何时应使用聚集索引或非聚集索引，但在实践中以上规则却很容易被忽视或不能根据实际情况进行综合分析。下面我们将根据在实践中遇到的实际问题来谈一下索引使用的误区，以便于大家掌握索引建立的方法。</div>
		<div>
				<b>1</b>
				<b>、主键就是聚集索引</b>
		</div>
		<div>这种想法笔者认为是极端错误的，是对聚集索引的一种浪费。虽然<span>SQL SERVER默认是在主键上建立聚集索引的。</span></div>
		<div>通常，我们会在每个表中都建立一个<span>ID列，以区分每条数据，并且这个ID列是自动增大的，步长一般为1。我们的这个办公自动化的实例中的列Gid就是如此。此时，如果我们将这个列设为主键，SQL SERVER会将此列默认为聚集索引。这样做有好处，就是可以让您的数据在数据库中按照ID进行物理排序，但笔者认为这样做意义不大。</span></div>
		<div>显而易见，聚集索引的优势是很明显的，而每个表中只能有一个聚集索引的规则，这使得聚集索引变得更加珍贵。</div>
		<div>从我们前面谈到的聚集索引的定义我们可以看出，使用聚集索引的最大好处就是能够根据查询要求，迅速缩小查询范围，避免全表扫描。在实际应用中，因为<span>ID号是自动生成的，我们并不知道每条记录的ID号，所以我们很难在实践中用ID号来进行查询。这就使让ID号这个主键作为聚集索引成为一种资源浪费。其次，让每个ID号都不同的字段作为聚集索引也不符合“大数目的不同值情况下不应建立聚合索引”规则；当然，这种情况只是针对用户经常修改记录内容，特别是索引项的时候会负作用，但对于查询速度并没有影响。</span></div>
		<div>在办公自动化系统中，无论是系统首页显示的需要用户签收的文件、会议还是用户进行文件查询等任何情况下进行数据查询都离不开字段的是“日期”还有用户本身的“用户名”。</div>
		<div>通常，办公自动化的首页会显示每个用户尚未签收的文件或会议。虽然我们的<span>where语句可以仅仅限制当前用户尚未签收的情况，但如果您的系统已建立了很长时间，并且数据量很大，那么，每次每个用户打开首页的时候都进行一次全表扫描，这样做意义是不大的，绝大多数的用户1个月前的文件都已经浏览过了，这样做只能徒增数据库的开销而已。事实上，我们完全可以让用户打开系统首页时，数据库仅仅查询这个用户近3个月来未阅览的文件，通过“日期”这个字段来限制表扫描，提高查询速度。如果您的办公自动化系统已经建立的2年，那么您的首页显示速度理论上将是原来速度8倍，甚至更快。</span></div>
		<div>在这里之所以提到“理论上”三字，是因为如果您的聚集索引还是盲目地建在<span>ID这个主键上时，您的查询速度是没有这么高的，即使您在“日期”这个字段上建立的索引（非聚合索引）。下面我们就来看一下在1000万条数据量的情况下各种查询的速度表现（3个月内的数据为25万条）：</span></div>
		<div>（<span>1）仅在主键上建立聚集索引，并且不划分时间段：</span></div>
		<div>Select gid,fariqi,neibuyonghu,title from tgongwen</div>
		<div>用时：<span>128470毫秒（即：128秒）</span></div>
		<div>（<span>2）在主键上建立聚集索引，在fariq上建立非聚集索引：</span></div>
		<div>select gid,fariqi,neibuyonghu,title from Tgongwen</div>
		<div>where fariqi&gt; dateadd(day,-90,getdate())</div>
		<div>用时：<span>53763毫秒（54秒）</span></div>
		<div>（<span>3）将聚合索引建立在日期列（fariqi）上：</span></div>
		<div>select gid,fariqi,neibuyonghu,title from Tgongwen</div>
		<div>where fariqi&gt; dateadd(day,-90,getdate())</div>
		<div>用时：<span>2423毫秒（2秒）</span></div>
		<div>虽然每条语句提取出来的都是<span>25万条数据，各种情况的差异却是巨大的，特别是将聚集索引建立在日期列时的差异。事实上，如果您的数据库真的有1000万容量的话，把主键建立在ID列上，就像以上的第1、2种情况，在网页上的表现就是超时，根本就无法显示。这也是我摒弃ID列作为聚集索引的一个最重要的因素。</span></div>
		<div>得出以上速度的方法是：在各个<span>select语句前加：declare @d datetime</span></div>
		<div>set @d=getdate()</div>
		<div>并在<span>select语句后加：</span></div>
		<div>select [语句执行花费时间<span>(毫秒)]=datediff(ms,@d,getdate())</span></div>
		<div>
				<b>2</b>
				<b>、只要建立索引就能显著提高查询速度</b>
		</div>
		<div>事实上，我们可以发现上面的例子中，第<span>2、3条语句完全相同，且建立索引的字段也相同；不同的仅是前者在fariqi字段上建立的是非聚合索引，后者在此字段上建立的是聚合索引，但查询速度却有着天壤之别。所以，并非是在任何字段上简单地建立索引就能提高查询速度。</span></div>
		<div>从建表的语句中，我们可以看到这个有着<span>1000万数据的表中fariqi字段有5003个不同记录。在此字段上建立聚合索引是再合适不过了。在现实中，我们每天都会发几个文件，这几个文件的发文日期就相同，这完全符合建立聚集索引要求的：“既不能绝大多数都相同，又不能只有极少数相同”的规则。由此看来，我们建立“适当”的聚合索引对于我们提高查询速度是非常重要的。</span></div>
		<div>
				<b>3</b>
				<b>、把所有需要提高查询速度的字段都加进聚集索引，以提高查询速度</b>
		</div>
		<div>上面已经谈到：在进行数据查询时都离不开字段的是“日期”还有用户本身的“用户名”。既然这两个字段都是如此的重要，我们可以把他们合并起来，建立一个复合索引（<span>compound index）。</span></div>
		<div>很多人认为只要把任何字段加进聚集索引，就能提高查询速度，也有人感到迷惑：如果把复合的聚集索引字段分开查询，那么查询速度会减慢吗？带着这个问题，我们来看一下以下的查询速度（结果集都是<span>25万条数据）：（日期列fariqi首先排在复合聚集索引的起始列，用户名neibuyonghu排在后列）</span></div>
		<div>（<span>1）select gid,fariqi,neibuyonghu,title from Tgongwen where fariqi&gt;'2004-5-5' </span></div>
		<div>查询速度：<span>2513毫秒</span></div>
		<div>（<span>2）select gid,fariqi,neibuyonghu,title from Tgongwen where fariqi&gt;'2004-5-5' and neibuyonghu='办公室'</span></div>
		<div>查询速度：<span>2516毫秒</span></div>
		<div>（<span>3）select gid,fariqi,neibuyonghu,title from Tgongwen where neibuyonghu='办公室'</span></div>
		<div>查询速度：<span>60280毫秒</span></div>
		<div>从以上试验中，我们可以看到如果仅用聚集索引的起始列作为查询条件和同时用到复合聚集索引的全部列的查询速度是几乎一样的，甚至比用上全部的复合索引列还要略快（在查询结果集数目一样的情况下）；而如果仅用复合聚集索引的非起始列作为查询条件的话，这个索引是不起任何作用的。当然，语句<span>1、2的查询速度一样是因为查询的条目数一样，如果复合索引的所有列都用上，而且查询结果少的话，这样就会形成“索引覆盖”，因而性能可以达到最优。同时，请记住：无论您是否经常使用聚合索引的其他列，但其前导列一定要是使用最频繁的列。</span></div>
		<div>
				<b>（四）其他书上没有的索引使用经验总结</b>
		</div>
		<div>
				<b>1</b>
				<b>、用聚合索引比用不是聚合索引的主键速度快</b>
		</div>
		<div>下面是实例语句：（都是提取<span>25万条数据）</span></div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where fariqi='2004-9-16'</div>
		<div>使用时间：<span>3326毫秒</span></div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where gid&lt;=250000</div>
		<div>使用时间：<span>4470毫秒</span></div>
		<div>这里，用聚合索引比用不是聚合索引的主键速度快了近<span>1/4。</span></div>
		<div>
				<b>2</b>
				<b>、用聚合索引比用一般的主键作<span>order by时速度快，特别是在小数据量情况下</span></b>
		</div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen order by fariqi</div>
		<div>用时：<span>12936</span></div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen order by gid</div>
		<div>用时：<span>18843</span></div>
		<div>这里，用聚合索引比用一般的主键作<span>order by时，速度快了3/10。事实上，如果数据量很小的话，用聚集索引作为排序列要比使用非聚集索引速度快得明显的多；而数据量如果很大的话，如10万以上，则二者的速度差别不明显。</span></div>
		<div>
				<b>3</b>
				<b>、使用聚合索引内的时间段，搜索时间会按数据占整个数据表的百分比成比例减少，而无论聚合索引使用了多少个</b>
		</div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where fariqi&gt;'2004-1-1'</div>
		<div>用时：<span>6343毫秒（提取100万条） </span></div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where fariqi&gt;'2004-6-6'</div>
		<div>用时：<span>3170毫秒（提取50万条）</span></div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where fariqi='2004-9-16'</div>
		<div>用时：<span>3326毫秒（和上句的结果一模一样。如果采集的数量一样，那么用大于号和等于号是一样的）</span></div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where fariqi&gt;'2004-1-1' and fariqi&lt;'2004-6-6'</div>
		<div>用时：<span>3280毫秒</span></div>
		<div>
				<b>4 </b>
				<b>、日期列不会因为有分秒的输入而减慢查询速度</b>
		</div>
		<div>下面的例子中，共有<span>100万条数据，2004年1月1日以后的数据有50万条，但只有两个不同的日期，日期精确到日；之前有数据50万条，有5000个不同的日期，日期精确到秒。</span></div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where fariqi&gt;'2004-1-1' order by fariqi</div>
		<div>用时：<span>6390毫秒</span></div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where fariqi&lt;'2004-1-1' order by fariqi</div>
		<div>用时：<span>6453毫秒</span></div>
		<div>
				<b>（五）其他注意事项</b>
		</div>
		<div>“水可载舟，亦可覆舟”，索引也一样。索引有助于提高检索性能，但过多或不当的索引也会导致系统低效。因为用户在表中每加进一个索引，数据库就要做更多的工作。过多的索引甚至会导致索引碎片。</div>
		<div>所以说，我们要建立一个“适当”的索引体系，特别是对聚合索引的创建，更应精益求精，以使您的数据库能得到高性能的发挥。</div>
		<div>当然，在实践中，作为一个尽职的数据库管理员，您还要多测试一些方案，找出哪种方案效率最高、最为有效。</div>
		<div> </div>
		<div>二、改善<span>SQL语句</span></div>
		<div>很多人不知道<span>SQL语句在SQL SERVER中是如何执行的，他们担心自己所写的SQL语句会被SQL SERVER误解。比如：</span></div>
		<div>select * from table1 where name='zhangsan' and tID &gt; 10000</div>
		<div>和执行<span>:</span></div>
		<div>select * from table1 where tID &gt; 10000 and name='zhangsan'</div>
		<div>一些人不知道以上两条语句的执行效率是否一样，因为如果简单的从语句先后上看，这两个语句的确是不一样，如果<span>tID是一个聚合索引，那么后一句仅仅从表的10000条以后的记录中查找就行了；而前一句则要先从全表中查找看有几个name='zhangsan'的，而后再根据限制条件条件tID&gt;10000来提出查询结果。</span></div>
		<div>事实上，这样的担心是不必要的。<span>SQL SERVER中有一个“查询分析优化器”，它可以计算出where子句中的搜索条件并确定哪个索引能缩小表扫描的搜索空间，也就是说，它能实现自动优化。</span></div>
		<div>虽然查询优化器可以根据<span>where子句自动的进行查询优化，但大家仍然有必要了解一下“查询优化器”的工作原理，如非这样，有时查询优化器就会不按照您的本意进行快速查询。</span></div>
		<div>在查询分析阶段，查询优化器查看查询的每个阶段并决定限制需要扫描的数据量是否有用。如果一个阶段可以被用作一个扫描参数（<span>SARG），那么就称之为可优化的，并且可以利用索引快速获得所需数据。</span></div>
		<div>SARG的定义：用于限制搜索的一个操作，因为它通常是指一个特定的匹配，一个值得范围内的匹配或者两个以上条件的<span>AND连接。形式如下：</span></div>
		<div>列名 操作符<span> &lt;常数 或 变量&gt;</span></div>
		<div>或</div>
		<div>&lt;常数 或 变量<span>&gt; 操作符列名</span></div>
		<div>列名可以出现在操作符的一边，而常数或变量出现在操作符的另一边。如：</div>
		<div>Name=’张三’</div>
		<div>价格<span>&gt;5000</span></div>
		<div>5000&lt;价格</div>
		<div>Name=’张三’ and 价格<span>&gt;5000</span></div>
		<div>如果一个表达式不能满足<span>SARG的形式，那它就无法限制搜索的范围了，也就是SQL SERVER必须对每一行都判断它是否满足WHERE子句中的所有条件。所以一个索引对于不满足SARG形式的表达式来说是无用的。</span></div>
		<div>介绍完<span>SARG后，我们来总结一下使用SARG以及在实践中遇到的和某些资料上结论不同的经验：</span></div>
		<div>
				<b>1</b>
				<b>、<span>Like语句是否属于SARG取决于所使用的通配符的类型</span></b>
		</div>
		<div>如：<span>name like </span>‘张<span>%</span>’ ，这就属于<span>SARG</span></div>
		<div>而：<span>name like </span>‘%张’ ,就不属于<span>SARG。</span></div>
		<div>原因是通配符<span>%在字符串的开通使得索引无法使用。</span></div>
		<div>
				<b>2</b>
				<b>、<span>or 会引起全表扫描</span></b>
		</div>
		<div>Name=’张三’ and 价格<span>&gt;5000 符号SARG，而：Name=</span>’张三’ or 价格<span>&gt;5000 则不符合SARG。使用or会引起全表扫描。</span></div>
		<div>
				<b>3</b>
				<b>、非操作符、函数引起的不满足<span>SARG形式的语句</span></b>
		</div>
		<div>不满足<span>SARG形式的语句最典型的情况就是包括非操作符的语句，如：NOT、!=、&lt;&gt;、!&lt;、!&gt;、NOT EXISTS、NOT IN、NOT LIKE等，另外还有函数。下面就是几个不满足SARG形式的例子：</span></div>
		<div>ABS(价格<span>)&lt;5000</span></div>
		<div>Name like ‘%三’</div>
		<div>有些表达式，如：</div>
		<div>WHERE 价格<span>*2&gt;5000</span></div>
		<div>SQL SERVER也会认为是<span>SARG，SQL SERVER会将此式转化为：</span></div>
		<div>WHERE 价格<span>&gt;2500/2</span></div>
		<div>但我们不推荐这样使用，因为有时<span>SQL SERVER不能保证这种转化与原始表达式是完全等价的。</span></div>
		<div>
				<b>4</b>
				<b>、<span>IN 的作用相当与OR</span></b>
		</div>
		<div>语句：</div>
		<div>Select * from table1 where tid in (2,3)</div>
		<div>和</div>
		<div>Select * from table1 where tid=2 or tid=3</div>
		<div>是一样的，都会引起全表扫描，如果<span>tid上有索引，其索引也会失效。</span></div>
		<div>
				<b>5</b>
				<b>、尽量少用<span>NOT</span></b>
		</div>
		<div>
				<b>6</b>
				<b>、<span>exists 和 in 的执行效率是一样的</span></b>
		</div>
		<div>很多资料上都显示说，<span>exists要比in的执行效率要高，同时应尽可能的用not exists来代替not in。但事实上，我试验了一下，发现二者无论是前面带不带not，二者之间的执行效率都是一样的。因为涉及子查询，我们试验这次用SQL SERVER自带的pubs数据库。运行前我们可以把SQL SERVER的statistics I/O状态打开。</span></div>
		<div>（<span>1）select title,price from titles where title_id in (select title_id from sales where qty&gt;30)</span></div>
		<div>
				<div>该句的执行结果为：</div>
		</div>
		<div>表<span> 'sales'。扫描计数 18，逻辑读 56 次，物理读 0 次，预读 0 次。</span></div>
		<div>
				<div>表<span> 'titles'。扫描计数 1，逻辑读 2 次，物理读 0 次，预读 0 次。</span></div>
		</div>
		<div>
				<span>    </span>
		</div>
		<div>（<span>2）select title,price from titles where exists (select * from sales where sales.title_id=titles.title_id and qty&gt;30)</span></div>
		<div>
				<div>第二句的执行结果为：</div>
		</div>
		<div>表<span> 'sales'。扫描计数 18，逻辑读 56 次，物理读 0 次，预读 0 次。</span></div>
		<div>
				<div>表<span> 'titles'。扫描计数 1，逻辑读 2 次，物理读 0 次，预读 0 次。</span></div>
		</div>
		<div>我们从此可以看到用<span>exists和用in的执行效率是一样的。</span></div>
		<div>
				<b>7</b>
				<b>、用函数<span>charindex()和前面加通配符%的LIKE执行效率一样</span></b>
		</div>
		<div>前面，我们谈到，如果在<span>LIKE前面加上通配符%，那么将会引起全表扫描，所以其执行效率是低下的。但有的资料介绍说，用函数charindex()来代替LIKE速度会有大的提升，经我试验，发现这种说明也是错误的：</span></div>
		<div>select gid,title,fariqi,reader from tgongwen where charindex('刑侦支队<span>',reader)&gt;0 and fariqi&gt;'2004-5-5'</span></div>
		<div>用时：<span>7秒，另外：扫描计数 4，逻辑读 7155 次，物理读 0 次，预读 0 次。</span></div>
		<div>select gid,title,fariqi,reader from tgongwen where reader like '%' + '刑侦支队<span>' + '%' and fariqi&gt;'2004-5-5'</span></div>
		<div>用时：<span>7秒，另外：扫描计数 4，逻辑读 7155 次，物理读 0 次，预读 0 次。</span></div>
		<div>
				<b>8</b>
				<b>、<span>union并不绝对比or的执行效率高</span></b>
		</div>
		<div>我们前面已经谈到了在<span>where子句中使用or会引起全表扫描，一般的，我所见过的资料都是推荐这里用union来代替or。事实证明，这种说法对于大部分都是适用的。</span></div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where fariqi='2004-9-16' or gid&gt;9990000</div>
		<div>用时：<span>68秒。扫描计数 1，逻辑读 404008 次，物理读 283 次，预读 392163 次。</span></div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where fariqi='2004-9-16' </div>
		<div>union</div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where gid&gt;9990000</div>
		<div>用时：<span>9秒。扫描计数 8，逻辑读 67489 次，物理读 216 次，预读 7499 次。</span></div>
		<div>看来，用<span>union在通常情况下比用or的效率要高的多。</span></div>
		<div>但经过试验，笔者发现如果<span>or两边的查询列是一样的话，那么用union则反倒和用or的执行速度差很多，虽然这里union扫描的是索引，而or扫描的是全表。</span></div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where fariqi='2004-9-16' or fariqi='2004-2-5'</div>
		<div>用时：<span>6423毫秒。扫描计数 2，逻辑读 14726 次，物理读 1 次，预读 7176 次。</span></div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where fariqi='2004-9-16' </div>
		<div>union</div>
		<div>select gid,fariqi,neibuyonghu,reader,title from Tgongwen where fariqi='2004-2-5'</div>
		<div>用时：<span>11640毫秒。扫描计数 8，逻辑读 14806 次，物理读 108 次，预读 1144 次。</span></div>
		<div>
				<b>9</b>
				<b>、字段提取要按照“需多少、提多少”的原则，避免“<span>select *”</span></b>
		</div>
		<div>我们来做一个试验：</div>
		<div>select top 10000 gid,fariqi,reader,title from tgongwen order by gid desc</div>
		<div>用时：<span>4673毫秒</span></div>
		<div>select top 10000 gid,fariqi,title from tgongwen order by gid desc</div>
		<div>用时：<span>1376毫秒</span></div>
		<div>select top 10000 gid,fariqi from tgongwen order by gid desc</div>
		<div>用时：<span>80毫秒</span></div>
		<div>由此看来，我们每少提取一个字段，数据的提取速度就会有相应的提升。提升的速度还要看您舍弃的字段的大小来判断。</div>
		<div>
				<b>10</b>
				<b>、<span>count(*)不比count(字段)慢</span></b>
		</div>
		<div>某些资料上说：用<span>*会统计所有列，显然要比一个世界的列名效率低。这种说法其实是没有根据的。我们来看：</span></div>
		<div>select count(*) from Tgongwen</div>
		<div>用时：<span>1500毫秒</span></div>
		<div>select count(gid) from Tgongwen </div>
		<div>用时：<span>1483毫秒</span></div>
		<div>select count(fariqi) from Tgongwen</div>
		<div>用时：<span>3140毫秒</span></div>
		<div>select count(title) from Tgongwen</div>
		<div>用时：<span>52050毫秒</span></div>
		<div>从以上可以看出，如果用<span>count(*)和用count(主键)的速度是相当的，而count(*)却比其他任何除主键以外的字段汇总速度要快，而且字段越长，汇总的速度就越慢。我想，如果用count(*)， SQL SERVER可能会自动查找最小字段来汇总的。当然，如果您直接写count(主键)将会来的更直接些。</span></div>
		<div>
				<b>11</b>
				<b>、<span>order by按聚集索引列排序效率最高</span></b>
		</div>
		<div>我们来看：（<span>gid是主键，fariqi是聚合索引列）</span></div>
		<div>select top 10000 gid,fariqi,reader,title from tgongwen</div>
		<div>用时：<span>196 毫秒。 扫描计数 1，逻辑读 289 次，物理读 1 次，预读 1527 次。</span></div>
		<div>select top 10000 gid,fariqi,reader,title from tgongwen order by gid asc</div>
		<div>用时：<span>4720毫秒。 扫描计数 1，逻辑读 41956 次，物理读 0 次，预读 1287 次。</span></div>
		<div>select top 10000 gid,fariqi,reader,title from tgongwen order by gid desc</div>
		<div>用时：<span>4736毫秒。 扫描计数 1，逻辑读 55350 次，物理读 10 次，预读 775 次。</span></div>
		<div>select top 10000 gid,fariqi,reader,title from tgongwen order by fariqi asc</div>
		<div>用时：<span>173毫秒。 扫描计数 1，逻辑读 290 次，物理读 0 次，预读 0 次。</span></div>
		<div>select top 10000 gid,fariqi,reader,title from tgongwen order by fariqi desc</div>
		<div>用时：<span>156毫秒。 扫描计数 1，逻辑读 289 次，物理读 0 次，预读 0 次。</span></div>
		<div>从以上我们可以看出，不排序的速度以及逻辑读次数都是和“<span>order by 聚集索引列” 的速度是相当的，但这些都比“order by 非聚集索引列”的查询速度是快得多的。</span></div>
		<div>同时，按照某个字段进行排序的时候，无论是正序还是倒序，速度是基本相当的。</div>
		<div>
				<b>12</b>
				<b>、高效的<span>TOP</span></b>
		</div>
		<div>事实上，在查询和提取超大容量的数据集时，影响数据库响应时间的最大因素不是数据查找，而是物理的<span>I/0操作。如：</span></div>
		<div>select top 10 * from (</div>
		<div>select top 10000 gid,fariqi,title from tgongwen</div>
		<div>where neibuyonghu='办公室<span>'</span></div>
		<div>order by gid desc) as a</div>
		<div>order by gid asc</div>
		<div>这条语句，从理论上讲，整条语句的执行时间应该比子句的执行时间长，但事实相反。因为，子句执行后返回的是<span>10000条记录，而整条语句仅返回10条语句，所以影响数据库响应时间最大的因素是物理I/O操作。而限制物理I/O操作此处的最有效方法之一就是使用TOP关键词了。TOP关键词是SQL SERVER中经过系统优化过的一个用来提取前几条或前几个百分比数据的词。经笔者在实践中的应用，发现TOP确实很好用，效率也很高。但这个词在另外一个大型数据库ORACLE中却没有，这不能说不是一个遗憾，虽然在ORACLE中可以用其他方法（如：rownumber）来解决。在以后的关于“实现千万级数据的分页显示存储过程”的讨论中，我们就将用到TOP这个关键词。</span></div>
		<div> </div>
		<div>到此为止，我们上面讨论了如何实现从大容量的数据库中快速地查询出您所需要的数据方法。当然，我们介绍的这些方法都是“软”方法，在实践中，我们还要考虑各种“硬”因素，如：网络性能、服务器的性能、操作系统的性能，甚至网卡、交换机等。</div>
		<div> </div>
		<div>三、实现小数据量和海量数据的通用分页显示存储过程</div>
		<div>建立一个<span>web 应用，分页浏览功能必不可少。这个问题是数据库处理中十分常见的问题。经典的数据分页方法是:ADO</span> 纪录集分页法，也就是利用<span>ADO自带的分页功能（利用游标）来实现分页。但这种分页方法仅适用于较小数据量的情形，因为游标本身有缺点：游标是存放在内存中，很费内存。游标一建立，就将相关的记录锁住，直到取消游标。游标提供了对特定集合中逐行扫描的手段，一般使用游标来逐行遍历数据，根据取出数据条件的不同进行不同的操作。而对于多表和大表中定义的游标（大的数据集合）循环很容易使程序进入一个漫长的等待甚至死机。</span></div>
		<div>更重要的是，对于非常大的数据模型而言，分页检索时，如果按照传统的每次都加载整个数据源的方法是非常浪费资源的。现在流行的分页方法一般是检索页面大小的块区的数据，而非检索所有的数据，然后单步执行当前行。</div>
		<div>
				<span>    </span>最早较好地实现这种根据页面大小和页码来提取数据的方法大概就是“俄罗斯存储过程”。这个存储过程用了游标，由于游标的局限性，所以这个方法并没有得到大家的普遍认可。</div>
		<div>
				<div>后来，网上有人改造了此存储过程，下面的存储过程就是结合我们的办公自动化实例写的分页存储过程：</div>
		</div>
		<div>CREATE procedure pagination1</div>
		<div>(@pagesize int, --页面大小，如每页存储<span>20条记录</span></div>
		<div>@pageindex int<span>   --</span>当前页码</div>
		<div>)</div>
		<div>as</div>
		<div>set nocount on</div>
		<div>begin</div>
		<div>declare @indextable table(id int identity(1,1),nid int) --定义表变量</div>
		<div>declare @PageLowerBound int --定义此页的底码</div>
		<div>declare @PageUpperBound int --定义此页的顶码</div>
		<div>set @PageLowerBound=(@pageindex-1)*@pagesize</div>
		<div>set @PageUpperBound=@PageLowerBound+@pagesize</div>
		<div>set rowcount @PageUpperBound</div>
		<div>insert into @indextable(nid) select gid from TGongwen where fariqi &gt;dateadd(day,-365,getdate()) order by fariqi desc</div>
		<div>select O.gid,O.mid,O.title,O.fadanwei,O.fariqi from TGongwen O,@indextable t where O.gid=t.nid</div>
		<div>and t.id&gt;@PageLowerBound and t.id&lt;=@PageUpperBound order by t.id</div>
		<div>end</div>
		<div>
				<div>set nocount off</div>
		</div>
		<div>以上存储过程运用了<span>SQL SERVER的最新技术</span>――表变量。应该说这个存储过程也是一个非常优秀的分页存储过程。当然，在这个过程中，您也可以把其中的表变量写成临时表：<span>CREATE TABLE #Temp。但很明显，在SQL SERVER中，用临时表是没有用表变量快的。所以笔者刚开始使用这个存储过程时，感觉非常的不错，速度也比原来的ADO的好。但后来，我又发现了比此方法更好的方法。</span></div>
		<div>
				<div>笔者曾在网上看到了一篇小短文《<span>从数据表中取出第<span>n条到第m条的记录的方法》，全文如下：</span></span></div>
		</div>
		<div>从<span>publish 表中取出第 n 条到第 m 条的记录： <br />SELECT TOP m-n+1 * <br />FROM publish <br />WHERE (id NOT IN <br />　　　　(SELECT TOP n-1 id <br />　　　　 FROM publish)) </span></div>
		<div>id 为<span>publish 表的关键字 </span></div>
		<div>
				<div>我当时看到这篇文章的时候，真的是精神为之一振，觉得思路非常得好。等到后来，我在作办公自动化系统（<span>ASP.NET+ C#＋SQL SERVER）的时候，忽然想起了这篇文章，我想如果把这个语句改造一下，这就可能是一个非常好的分页存储过程。于是我就满网上找这篇文章，没想到，文章还没找到，却找到了一篇根据此语句写的一个分页存储过程，这个存储过程也是目前较为流行的一种分页存储过程，我很后悔没有争先把这段文字改造成存储过程：</span></div>
		</div>
		<div>CREATE PROCEDURE pagination2<br />(<br /> @SQL nVARCHAR(4000),<span>    --</span>不带排序语句的<span>SQL语句<br /></span> @Page int,<span>              --</span>页码<span><br /></span> @RecsPerPage int,<span>       --</span>每页容纳的记录数<span><br /></span> @ID VARCHAR(255),<span>       --</span>需要排序的不重复的<span>ID号<br /></span> @Sort VARCHAR(255)<span>      --</span>排序字段及规则<span><br />)<br />AS</span></div>
		<div>DECLARE @Str nVARCHAR(4000)</div>
		<div>SET @Str='SELECT   TOP '+CAST(@RecsPerPage AS VARCHAR(20))+' * FROM ('+@SQL+') T WHERE T.'+@ID+'NOT IN <br />(SELECT   TOP '+CAST((@RecsPerPage*(@Page-1)) AS VARCHAR(20))+' '+@ID+' FROM ('+@SQL+') T9 ORDER BY '+@Sort+') ORDER BY '+@Sort</div>
		<div>PRINT @Str</div>
		<div>
				<div>EXEC sp_ExecuteSql @Str<br />GO</div>
		</div>
		<div>其实，以上语句可以简化为：</div>
		<div>SELECT TOP 页大小<span> *</span></div>
		<div>FROM Table1</div>
		<div>WHERE (ID NOT IN</div>
		<div>
				<span>          (SELECT TOP </span>页大小<span>*页数 id</span></div>
		<div>
				<span>         FROM </span>表</div>
		<div>
				<span>         ORDER BY id))</span>
		</div>
		<div>ORDER BY ID</div>
		<div>但这个存储过程有一个致命的缺点，就是它含有<span>NOT IN字样。虽然我可以把它改造为：</span></div>
		<div>SELECT TOP 页大小<span> *</span></div>
		<div>FROM Table1</div>
		<div>WHERE not exists</div>
		<div>(select * from (select top (页大小<span>*页数) * from table1 order by id) b where b.id=a.id )</span></div>
		<div>order by id</div>
		<div>即，用<span>not exists来代替not in，但我们前面已经谈过了，二者的执行效率实际上是没有区别的。</span></div>
		<div>既便如此，用<span>TOP 结合NOT IN的这个方法还是比用游标要来得快一些。</span></div>
		<div>虽然用<span>not exists并不能挽救上个存储过程的效率，但使用SQL SERVER中的TOP关键字却是一个非常明智的选择。因为分页优化的最终目的就是避免产生过大的记录集，而我们在前面也已经提到了TOP的优势，通过TOP 即可实现对数据量的控制。</span></div>
		<div>在分页算法中，影响我们查询速度的关键因素有两点：<span>TOP和NOT IN。TOP可以提高我们的查询速度，而NOT IN会减慢我们的查询速度，所以要提高我们整个分页算法的速度，就要彻底改造NOT IN，同其他方法来替代它。</span></div>
		<div>我们知道，几乎任何字段，我们都可以通过<span>max(字段)或min(字段)来提取某个字段中的最大或最小值，所以如果这个字段不重复，那么就可以利用这些不重复的字段的max或min作为分水岭，使其成为分页算法中分开每页的参照物。在这里，我们可以用操作符“&gt;”或“&lt;”号来完成这个使命，使查询语句符合SARG形式。如：</span></div>
		<div>Select top 10 * from table1 where id&gt;<span>200</span></div>
		<div>于是就有了如下分页方案：</div>
		<div>select top 页大小<span> *</span></div>
		<div>from table1 </div>
		<div>where id&gt;</div>
		<div>
				<span>      (select max (id) from </span>
		</div>
		<div>
				<span>      (select top ((</span>页码<span>-1)*页大小) id from table1 order by id) as T</span></div>
		<div>
				<span>       )     </span>
		</div>
		<div>  order by id</div>
		<div>在选择即不重复值，又容易分辨大小的列时，我们通常会选择主键。下表列出了笔者用有着<span>1000万数据的办公自动化系统中的表，在以GID（GID是主键，但并不是聚集索引。）为排序列、提取gid,fariqi,title字段，分别以第1、10、100、500、1000、1万、10万、25万、50万页为例，测试以上三种分页方案的执行速度：（单位：毫秒）</span></div>
		<p>
		</p>
		<table cellspacing="0" cellpadding="0" border="1">
				<tbody>
						<tr>
								<td valign="top" width="142">
										<div align="center">页<span> 码</span></div>
								</td>
								<td valign="top" width="142">
										<div align="center">方案<span>1</span></div>
								</td>
								<td valign="top" width="142">
										<div align="center">方案<span>2</span></div>
								</td>
								<td valign="top" width="142">
										<div align="center">方案<span>3</span></div>
								</td>
						</tr>
						<tr>
								<td valign="top" width="142">
										<div align="center">1</div>
								</td>
								<td valign="top" width="142">
										<div align="center">60</div>
								</td>
								<td valign="top" width="142">
										<div align="center">30</div>
								</td>
								<td valign="top" width="142">
										<div align="center">76</div>
								</td>
						</tr>
						<tr>
								<td valign="top" width="142">
										<div align="center">10</div>
								</td>
								<td valign="top" width="142">
										<div align="center">46</div>
								</td>
								<td valign="top" width="142">
										<div align="center">16</div>
								</td>
								<td valign="top" width="142">
										<div align="center">63</div>
								</td>
						</tr>
						<tr>
								<td valign="top" width="142">
										<div align="center">100</div>
								</td>
								<td valign="top" width="142">
										<div align="center">1076</div>
								</td>
								<td valign="top" width="142">
										<div align="center">720</div>
								</td>
								<td valign="top" width="142">
										<div align="center">130</div>
								</td>
						</tr>
						<tr>
								<td valign="top" width="142">
										<div align="center">500</div>
								</td>
								<td valign="top" width="142">
										<div align="center">540</div>
								</td>
								<td valign="top" width="142">
										<div align="center">12943</div>
								</td>
								<td valign="top" width="142">
										<div align="center">83</div>
								</td>
						</tr>
						<tr>
								<td valign="top" width="142">
										<div align="center">1000</div>
								</td>
								<td valign="top" width="142">
										<div align="center">17110</div>
								</td>
								<td valign="top" width="142">
										<div align="center">470</div>
								</td>
								<td valign="top" width="142">
										<div align="center">250</div>
								</td>
						</tr>
						<tr>
								<td valign="top" width="142">
										<div align="center">1万</div>
								</td>
								<td valign="top" width="142">
										<div align="center">24796</div>
								</td>
								<td valign="top" width="142">
										<div align="center">4500</div>
								</td>
								<td valign="top" width="142">
										<div align="center">140</div>
								</td>
						</tr>
						<tr>
								<td valign="top" width="142">
										<div align="center">10万</div>
								</td>
								<td valign="top" width="142">
										<div align="center">38326</div>
								</td>
								<td valign="top" width="142">
										<div align="center">42283</div>
								</td>
								<td valign="top" width="142">
										<div align="center">1553</div>
								</td>
						</tr>
						<tr>
								<td valign="top" width="142">
										<div align="center">25万</div>
								</td>
								<td valign="top" width="142">
										<div align="center">28140</div>
								</td>
								<td valign="top" width="142">
										<div align="center">128720</div>
								</td>
								<td valign="top" width="142">
										<div align="center">2330</div>
								</td>
						</tr>
						<tr>
								<td valign="top" width="142">
										<div align="center">50万</div>
								</td>
								<td valign="top" width="142">
										<div align="center">121686</div>
								</td>
								<td valign="top" width="142">
										<div align="center">127846</div>
								</td>
								<td valign="top" width="142">
										<div align="center">7168</div>
								</td>
						</tr>
				</tbody>
		</table>
		<div>从上表中，我们可以看出，三种存储过程在执行<span>100页以下的分页命令时，都是可以信任的，速度都很好。但第一种方案在执行分页1000页以上后，速度就降了下来。第二种方案大约是在执行分页1万页以上后速度开始降了下来。而第三种方案却始终没有大的降势，后劲仍然很足。</span></div>
		<div>
				<div>在确定了第三种分页方案后，我们可以据此写一个存储过程。大家知道<span>SQL SERVER的存储过程是事先编译好的SQL语句，它的执行效率要比通过WEB页面传来的SQL语句的执行效率要高。下面的存储过程不仅含有分页方案，还会根据页面传来的参数来确定是否进行数据总数统计。</span></div>
		</div>
		<div>-- 获取指定页的数据</div>
		<div>CREATE PROCEDURE pagination3</div>
		<div>@tblName<span>   varchar(255),       -- </span>表名</div>
		<div>@strGetFields varchar(1000) = '*', -- 需要返回的列</div>
		<div>@fldName varchar(255)='',<span>      -- </span>排序的字段名</div>
		<div>@PageSize <span>  int = 10,          -- </span>页尺寸</div>
		<div>@PageIndex int = 1,<span>           -- </span>页码</div>
		<div>@doCount bit = 0,<span>   -- </span>返回记录总数<span>, 非 0 值则返回</span></div>
		<div>@OrderType bit = 0, -- 设置排序类型<span>, 非 0 值则降序</span></div>
		<div>@strWhere varchar(1500) = '' -- 查询条件<span> (注意: 不要加 where)</span></div>
		<div>AS</div>
		<div>declare @strSQL<span>   varchar(5000)       -- </span>主语句</div>
		<div>declare @strTmp<span>   varchar(110)        -- </span>临时变量</div>
		<div>declare @strOrder varchar(400)<span>        -- </span>排序类型</div>
		<div> </div>
		<div>if @doCount != 0</div>
		<div> begin</div>
		<div>
				<span>    if @strWhere !=''</span>
		</div>
		<div>
				<span>    set @strSQL = "select count(*) as Total from [" + @tblName + "] where "+@strWhere</span>
		</div>
		<div>
				<span>    else</span>
		</div>
		<div>
				<span>    set @strSQL = "select count(*) as Total from [" + @tblName + "]"</span>
		</div>
		<div>end </div>
		<div>--以上代码的意思是如果<span>@doCount传递过来的不是0，就执行总数统计。以下的所有代码都是@doCount为0的情况</span></div>
		<div>else</div>
		<div>begin</div>
		<div> </div>
		<div>if @OrderType != 0</div>
		<div>begin</div>
		<div>
				<span>    set @strTmp = "&lt;(select min"</span>
		</div>
		<div>set @strOrder = " order by [" + @fldName +"] desc"</div>
		<div>--如果<span>@OrderType不是0，就执行降序，这句很重要！</span></div>
		<div>end</div>
		<div>else</div>
		<div>begin</div>
		<div>
				<span>    set @strTmp = "&gt;(select max"</span>
		</div>
		<div>
				<span>    set @strOrder = " order by [" + @fldName +"] asc"</span>
		</div>
		<div>end</div>
		<div> </div>
		<div>if @PageIndex = 1</div>
		<div>begin</div>
		<div>
				<span>    if @strWhere != ''   </span>
		</div>
		<div>
				<span>    set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from [" + @tblName + "] where " + @strWhere + " " + @strOrder</span>
		</div>
		<div>
				<span>     else</span>
		</div>
		<div>
				<span>     set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from ["+ @tblName + "] "+ @strOrder</span>
		</div>
		<div>--如果是第一页就执行以上代码，这样会加快执行速度</div>
		<div>end</div>
		<div>else</div>
		<div>begin</div>
		<div>--以下代码赋予了<span>@strSQL以真正执行的SQL代码</span></div>
		<div>set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from ["</div>
		<div>
				<span>    + @tblName + "] where [" + @fldName + "]" + @strTmp + "(["+ @fldName + "]) from (select top " + str((@PageIndex-1)*@PageSize) + " ["+ @fldName + "] from [" + @tblName + "]" + @strOrder + ") as tblTmp)"+ @strOrder</span>
		</div>
		<div> </div>
		<div>if @strWhere != ''</div>
		<div>
				<span>    set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from ["</span>
		</div>
		<div>
				<span>        + @tblName + "] where [" + @fldName + "]" + @strTmp + "(["</span>
		</div>
		<div>
				<span>        + @fldName + "]) from (select top " + str((@PageIndex-1)*@PageSize) + " ["</span>
		</div>
		<div>
				<span>        + @fldName + "] from [" + @tblName + "] where " + @strWhere + " "</span>
		</div>
		<div>
				<span>        + @strOrder + ") as tblTmp) and " + @strWhere + " " + @strOrder</span>
		</div>
		<div>end </div>
		<div>end<span>   </span></div>
		<div>exec (@strSQL)</div>
		<div>
				<div>GO</div>
		</div>
		<div>上面的这个存储过程是一个通用的存储过程，其注释已写在其中了。</div>
		<div>在大数据量的情况下，特别是在查询最后几页的时候，查询时间一般不会超过<span>9秒；而用其他存储过程，在实践中就会导致超时，所以这个存储过程非常适用于大容量数据库的查询。</span></div>
		<div>笔者希望能够通过对以上存储过程的解析，能给大家带来一定的启示，并给工作带来一定的效率提升，同时希望同行提出更优秀的实时数据分页算法。</div>
		<div> </div>
		<div>四、聚集索引的重要性和如何选择聚集索引</div>
		<div>在上一节的标题中，笔者写的是：<b>实现小数据量和海量数据的通用分页显示存储过程。</b>这是因为在将本存储过程应用于“办公自动化”系统的实践中时，笔者发现这第三种存储过程在小数据量的情况下，有如下现象：</div>
		<div>1、分页速度一般维持在<span>1秒和3秒之间。</span></div>
		<div>2、在查询最后一页时，速度一般为<span>5秒至8秒，哪怕分页总数只有3页或30万页。</span></div>
		<div>虽然在超大容量情况下，这个分页的实现过程是很快的，但在分前几页时，这个<span>1－3秒的速度比起第一种甚至没有经过优化的分页方法速度还要慢，借用户的话说就是“还没有ACCESS数据库速度快”，这个认识足以导致用户放弃使用您开发的系统。</span></div>
		<div>笔者就此分析了一下，原来产生这种现象的症结是如此的简单，但又如此的重要：<b>排序的字段不是聚集索引！</b></div>
		<div>本篇文章的题目是：“查询优化及分页算法方案”。笔者只所以把“查询优化”和“分页算法”这两个联系不是很大的论题放在一起，就是因为二者都需要一个非常重要的东西――聚集索引。</div>
		<div>在前面的讨论中我们已经提到了，聚集索引有两个最大的优势：</div>
		<div>
				<b>1</b>
				<b>、以最快的速度缩小查询范围。</b>
		</div>
		<div>
				<b>2</b>
				<b>、以最快的速度进行字段排序。</b>
		</div>
		<div>第<span>1条多用在查询优化时，而第2条多用在进行分页时的数据排序。</span></div>
		<div>而聚集索引在每个表内又只能建立一个，这使得聚集索引显得更加的重要。聚集索引的挑选可以说是实现“查询优化”和“高效分页”的最关键因素。</div>
		<div>但要既使聚集索引列既符合查询列的需要，又符合排序列的需要，这通常是一个矛盾。</div>
		<div>笔者前面“索引”的讨论中，将<span>fariqi，即用户发文日期作为了聚集索引的起始列，日期的精确度为“日”。这种作法的优点，前面已经提到了，在进行划时间段的快速查询中，比用ID主键列有很大的优势。</span></div>
		<div>但在分页时，由于这个聚集索引列存在着重复记录，所以无法使用<span>max或min来最为分页的参照物，进而无法实现更为高效的排序。而如果将ID主键列作为聚集索引，那么聚集索引除了用以排序之外，没有任何用处，实际上是浪费了聚集索引这个宝贵的资源。</span></div>
		<div>为解决这个矛盾，笔者后来又添加了一个日期列，其默认值为<span>getdate()。用户在写入记录时，这个列自动写入当时的时间，时间精确到毫秒。即使这样，为了避免可能性很小的重合，还要在此列上创建UNIQUE约束。将此日期列作为聚集索引列。</span></div>
		<div>有了这个时间型聚集索引列之后，用户就既可以用这个列查找用户在插入数据时的某个时间段的查询，又可以作为唯一列来实现<span>max或min，成为分页算法的参照物。</span></div>
		<div>经过这样的优化，笔者发现，无论是大数据量的情况下还是小数据量的情况下，分页速度一般都是几十毫秒，甚至<span>0毫秒。而用日期段缩小范围的查询速度比原来也没有任何迟钝。</span></div>
		<div>聚集索引是如此的重要和珍贵，所以笔者总结了一下，一定要将聚集索引建立在：</div>
		<div>
				<b>1</b>
				<b>、您最频繁使用的、用以缩小查询范围的字段上；</b>
		</div>
		<div>
				<b>2</b>
				<b>、您最频繁使用的、需要排序的字段上。</b>
		</div>
		<div> </div>
		<div>
				<b>结束语：</b>
		</div>
		<div>本篇文章汇集了笔者近段在使用数据库方面的心得，是在做“办公自动化”系统时实践经验的积累。希望这篇文章不仅能够给大家的工作带来一定的帮助，也希望能让大家能够体会到分析问题的方法；最重要的是，希望这篇文章能够抛砖引玉，掀起大家的学习和讨论的兴趣，以共同促进，共同为公安科技强警事业和金盾工程做出自己最大的努力。</div>
		<div>最后需要说明的是，在试验中，我发现用户在进行大数据量查询的时候，对数据库速度影响最大的不是内存大小，而是<span>CPU。在我的P4 2.4机器上试验的时候，查看“资源管理器”，CPU经常出现持续到100%的现象，而内存用量却并没有改变或者说没有大的改变。即使在我们的HP ML 350 G3服务器上试验时，CPU峰值也能达到90%，一般持续在70%左右。</span></div>
		<div>本文的试验数据都是来自我们的<span>HP ML 350服务器。服务器配置：双Inter Xeon 超线程 CPU 2.4G，内存1G，操作系统Windows Server 2003 Enterprise Edition，数据库SQL Server 2000 SP3。</span></div>
		<div> </div>
		<div>大家可以访问以下公安网网址或互联网网址来体验一下我们的“千万级”数据库的办公自动化（<span>ASP.NET＋C#语言）。</span></div>
		<div>
				<a href="http://10.59.121.11:90/">
						<font color="#6600cc">http://10.59.121.11:90</font>
				</a>
		</div>
		<div>
				<a href="http://www.xx110.net/OA">
						<font color="#6600cc">http://www.xx110.net/OA</font>
				</a>
		</div>
<img src ="http://www.cnitblog.com/sfep/aggbug/7825.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/sfep/" target="_blank">不再回头</a> 2006-03-20 17:33 <a href="http://www.cnitblog.com/sfep/archive/2006/03/20/7825.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>