(喷血分享)利用.NET生成数据库表的创建脚本,类似SqlServer编写表的CREATE语句

  1. 云栖社区>
  2. 博客>
  3. 正文

(喷血分享)利用.NET生成数据库表的创建脚本,类似SqlServer编写表的CREATE语句

科技小先锋 2017-11-22 23:08:00 浏览874
展开阅读全文

(喷血分享)利用.NET生成数据库表的创建脚本,类似SqlServer编写表的CREATE语句


  在我们RDIFramework.NET代码生成器中,有这样一个应用,就是通过数据库表自动生成表的CREATE语句,如下图所示:

25152013-d3f04858b6c24af1be4b1ddb4436b19

  在实现此功能前摸索了很多方法,最后借助MSSQLSERVER自带的dll文件来完成。先截图展示下此功能生成后的效果,然后再分享代码与方法,欢迎大家讨论其他可行方式,谢谢。25152038-86c7cdd4b14e46b9b70fad8be229b18

  通过上图可以看到,生成的表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

如下图所示:

25152143-408eaa1099d5442db076692420a2f24

引用了上面两个dll文件后,在我们的项目中添加命名空间:

1
2
using Microsoft.SqlServer.Management.Common; 
using Microsoft.SqlServer.Management.Smo;


现在,我们就可以使用MSSQLSERVER提供的类库来生成表的CREATE语句了。

下面给出创建的全部代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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语句后的控件。


本文转自yonghu86 51CTO博客,原文链接:http://blog.51cto.com/yonghu/1321309,如需转载请自行联系原作者

网友评论

登录后评论
0/500
评论
科技小先锋
+ 关注