Example #1
0
        private void button2_Click(object sender, EventArgs e)
        {
            //如果没有选中表,则不执行
            if (string.IsNullOrEmpty(CurrentTableName.Text))
            {
                return;
            }

            //是否含有聚集索引
            bool hasClusteredIndex = (CSHelper.ifExist("select count(*) from sys.indexes where object_id=OBJECT_ID('" + CurrentTableName.Text + "') and type_desc='CLUSTERED'; ") == 1);
            //if (!hasClusteredIndex)
            //{
            //    MessageBox.Show("此表没有聚集索引,请先创建!");
            //    return;
            //}


            Thread worker = new Thread(delegate()
            {
                Stopwatch sw = new Stopwatch();
                try
                {
                    sw.Start();
                    ShowLoading(true);

                    if (hasClusteredIndex)
                    {
                        ApendLog(string.Format("正在对表[{0}]重建索引", CurrentTableName.Text));
                        CSHelper.exec_sql(string.Format("DBCC DBREINDEX ({0}, '', 90)  ", CurrentTableName.Text));
                    }
                    else
                    {
                        ApendLog(string.Format("准备对表[{0}]建立索引", CurrentTableName.Text));

                        var field = CSHelper.ExecuteScalar(string.Format("Select top 1 name from syscolumns Where ID=OBJECT_ID('{0}')", CurrentTableName.Text));
                        ApendLog(string.Format("查出表[{0}]第一个字段为:{1}", CurrentTableName.Text, field));
                        ApendLog(string.Format("正在为表[{0}]字段[{1}]建立临时ClusteredIndex索引...时间比较久", CurrentTableName.Text, field));
                        CSHelper.exec_sql(string.Format("create clustered index ClusteredIndex on {0}({1}) ", CurrentTableName.Text, field));

                        ApendLog(string.Format("删除临时索引中..."));
                        CSHelper.exec_sql(string.Format("DROP INDEX {0}.ClusteredIndex ", CurrentTableName.Text, field));
                    }
                }
                catch (Exception ex)
                {
                    ApendLog(ex.Message);
                }
                finally
                {
                    sw.Stop();
                    TimeSpan ts = sw.Elapsed;
                    ApendLog("重建索引完成,耗时:" + string.Format("{0}时{1}分{2}秒{3}毫秒", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds));
                    isRuning = false;
                }
            });

            worker.IsBackground = true;
            worker.Start();
            t          = new System.Timers.Timer(3000);
            t.Elapsed += t_Elapsed;
            t.Enabled  = true;
        }