利用.NET生成數據庫表的創建腳本,類似SqlServer編寫表的CREATE語句

(噴血分享)利用.NET生成數據庫表的創建腳本,類似SqlServer編寫表的CREATE語句

 

  在我們RDIFramework.NET代碼生成器中,有這樣一個應用,就是通過數據庫表自動生成表的CREATE語句,如下圖所示:

 

  在實現此功能前摸索了很多方法,最後藉助MSSQLSERVER自帶的dll文件來完成。先截圖展示下此功能生成後的效果,然後再分享代碼與方法,歡迎大家討論其他可行方式,謝謝。 

  通過上圖可以看到,生成的表CREATE語句與SQLSERVER企業管理器生成的語句完全一樣。現在我們來看一看如何實現。在上面我說過,我採用的是SQLSERVER自帶的dll文件的方法來完成。因此,我們首先要引用MSSQLSERVER的相關dll文件,如我的SQLSERVER安裝在“D:\Program Files\Microsoft SQL Server\”,打開目錄“D:\Program Files\Microsoft SQL Server\100\SDK\Assemblies”,就可以看到SQLSERVER的全部dll文件了,其實通過這些dll文件,我們可以完成像SQLSERVER企業管理器一樣的功能,非常強大,看你怎麼使用了,在此僅拋磚引玉。我們需要在我們的項目中添加兩個dll文件的引用,分別爲:

Microsoft.SqlServer.ConnectionInfo.dll

Microsoft.SqlServer.Management.Sdk.Sfc.dll

如下圖所示:

   

引用了上面兩個dll文件後,在我們的項目中添加命名空間:

using Microsoft.SqlServer.Management.Common;

using Microsoft.SqlServer.Management.Smo;

現在,我們就可以使用MSSQLSERVER提供的類庫來生成表的CREATE語句了。

下面給出創建的全部代碼:

複製代碼
     private void ScriptOption()
        {
            scriptOption.ContinueScriptingOnError = true;
            scriptOption.IncludeIfNotExists = true;
            scriptOption.NoCollation = true;
            scriptOption.ScriptDrops = false;
            scriptOption.ContinueScriptingOnError = true;
            //scriptOption.DriAllConstraints = true;
            scriptOption.WithDependencies = false;
            scriptOption.DriForeignKeys = true;
            scriptOption.DriPrimaryKey = true;
            scriptOption.DriDefaults = true;
            scriptOption.DriChecks = true;
            scriptOption.DriUniqueKeys = true;
            scriptOption.Triggers = true;
            scriptOption.ExtendedProperties = true;
            scriptOption.NoIdentities = false;
        }

        /// <summary>
        /// 生成數據庫類型爲SqlServer指定表的DDL
        /// </summary>
        private void GenerateSqlServerDDL()
        {
            //對於已經生成過的就不用再次生成了,節約資源。
            if (!string.IsNullOrEmpty(textEditorDDL.Text) && textEditorDDL.Text.Trim().Length > 10)
            {
                return;
            }

            ScriptOption();
            ServerConnection sqlConnection = null;
            try
            {
                StringBuilder sbOutPut = new StringBuilder();
                
                if (dbSet.ConnectStr.ToLower().Contains("integrated security")) //Windows身份驗證
                {
                    sqlConnection = new ServerConnection(dbSet.Server);
                }
                else        //SqlServer身份驗證
                {
                    string[] linkDataArray = dbSet.ConnectStr.Split(';');
                    string userName = string.Empty;
                    string pwd = string.Empty;
                    foreach (string str in linkDataArray)
                    { 
                        if(str.ToLower().Replace(" ","").Contains("userid="))
                        {
                            userName = str.Split('=')[1];
                        }

                        if (str.ToLower().Replace(" ", "").Contains("password"))
                        {
                            pwd = str.Split('=')[1];
                        }
                    }

                    sqlConnection = new ServerConnection(dbSet.Server,userName,pwd);
                }

                Server sqlServer = new Server(sqlConnection);
                Table table = sqlServer.Databases[dbSet.DbName].Tables[txtName.Text];
                string ids;
                //編寫表的腳本
                sbOutPut = new StringBuilder();
                sbOutPut.AppendLine();
                sCollection = table.Script(scriptOption);

                foreach (String str in sCollection)
                {
                    //此處修正smo的bug
                    if (str.Contains("ADD  DEFAULT") && str.Contains("') AND type = 'D'"))
                    {
                        ids = str.Substring(str.IndexOf("OBJECT_ID(N'") + "OBJECT_ID(N'".Length, str.IndexOf("') AND type = 'D'") - str.IndexOf("OBJECT_ID(N'") - "OBJECT_ID(N'".Length);
                        sbOutPut.AppendLine(str.Insert(str.IndexOf("ADD  DEFAULT") + 4, "CONSTRAINT " + ids));
                    }
                    else
                        sbOutPut.AppendLine(str);

                    sbOutPut.AppendLine("GO");
                }

                //生成存儲過程
                this.textEditorDDL.SetCodeEditorContent("SQL", sbOutPut.ToString());
                this.textEditorDDL.SaveFileName = this.TableName + ".sql";
                sbOutPut = new StringBuilder();
            }
            catch (Exception ex)
            {
                LogHelper.WriteException(ex);
            }
            finally
            {
                sqlConnection.Disconnect();
            }
        }
複製代碼

 

說明:textEditorDDL爲顯示生成表CREATE語句後的控件。

發佈了4 篇原創文章 · 獲贊 3 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章