11

在 SQL Server Management Studio 中,我可以CREATE TABLE通过右键单击表并选择Script Table As.

如何在 C# 中获得相同的结果?我可以使用 SMO 或其他方法吗?

[为避免问题被关闭,请发布工作代码示例,而不是单行代码或指向高级文档的链接。]

4

4 回答 4

9

以下代码将通过指定服务器“XXX”、表“ZZZ”和模式“PPP”在“QQQ”位置创建一个脚本。有一些示例脚本漂浮在那里,可以复制整个数据库,这仅适用于表。这就是我一直试图弄清楚的,我终于用下面的代码让它工作了。这是一个简单的示例,例如,生成的脚本不会创建表的索引,而只是创建其最基本的结构。要指定脚本的创建方式,请将 ScriptingOptions 的实例传递到对 table.Script() 的调用中。

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.SqlEnum;
using System.Configuration;
using System.Collections.Specialized;

namespace SmoTest {
    class Program {
        static void Main(string[] args) {

            Server server = new Server("XXX");
            Database database = new Database();
            database = server.Databases["YYY"];
            Table table = database.Tables["ZZZ", @"PPP"];

            StringCollection result = table.Script();

            var script = "";
            foreach (var line in result) {
                script += line;
            }

            System.IO.StreamWriter fs = System.IO.File.CreateText(@"QQQ");
            fs.Write(script);
            fs.Close();

        }
    }
}
于 2012-07-25T19:46:38.307 回答
6

这是一个稍微完整的例子(从我的朋友 Ben Miller 那里偷来的):

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.SqlEnum;
using Microsoft.SqlServer.Management.Smo.CoreEnum;
using System.Configuration;
using System.Collections.Specialized;

namespace SmoTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Server srv = new Server();

            // really you would get these from config or elsewhere:
            srv.ConnectionContext.Login = "foo";
            srv.ConnectionContext.Password = "bar";
            srv.ConnectionContext.ServerInstance = "ServerName";
            string dbName = "DatabaseName";

            Database db = new Database();
            db = srv.Databases[dbName];

            StringBuilder sb = new StringBuilder();

            foreach(Table tbl in db.Tables)
            {
                ScriptingOptions options = new ScriptingOptions();
                options.ClusteredIndexes = true;
                options.Default = true;
                options.DriAll = true;
                options.Indexes = true;
                options.IncludeHeaders = true;

                StringCollection coll = tbl.Script(options);
                foreach (string str in coll)
                {
                    sb.Append(str);
                    sb.Append(Environment.NewLine);
                }
            }
            System.IO.StreamWriter fs = System.IO.File.CreateText("c:\\temp\\output.txt");
            fs.Write(sb.ToString());
            fs.Close();
        }
    }
}
于 2012-07-25T20:27:05.223 回答
0

表脚本

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using Microsoft.SqlServer.Management.Smo; 
using Microsoft.SqlServer.Management.Sdk.Sfc; 
using Microsoft.SqlServer.Management.Common; 
using System.Collections.Specialized; 
using System.IO; 
using System.Data; 
using Microsoft.SqlServer.Management; 
using System.Data.SqlClient;

namespace GenrateScriptsForDatabase
{
    class Program
    {
        static void Main(string[] args)
        {

            var server = new Server(new ServerConnection { ConnectionString = new SqlConnectionStringBuilder { DataSource = @"Your Server Name", UserID="Your User Id",Password="Your Password" }.ToString() });
            server.ConnectionContext.Connect();
            var database = server.Databases["Your Database Name"];

            using (FileStream fs = new FileStream(@"H:\database_scripts\Gaurav.sql", FileMode.Append, FileAccess.Write))
            using (StreamWriter sw = new StreamWriter(fs))
            {
                for each (Table table in database.Tables)
                {
                    if (table.Name == "Your Table Name")
                    {
                        var scripter = new Scripter(server) { Options = { ScriptData = true } };
                        var script = scripter.EnumScript(new SqlSmoObject[] { table });
                        for each (string line in script)
                        {

                                sw.WriteLine(line);
                                Console.WriteLine(line);
                            }
                        }
                    }
                }
            }
        }
}
于 2017-03-03T12:58:18.520 回答
0

您可以尝试以下函数以使用 C# 从 SQL Server 数据库获取表脚本。完整文章:在两个 SQL Server 数据库之间传输数据或脚本

C#代码:

公共字符串GetTableScript(字符串表名,字符串连接字符串)
{
    字符串脚本 = "";

    字符串 Sql = "声明@table varchar(100)" + Environment.NewLine +
    "set @table = '" + TableName + "'" + Environment.NewLine +
        //"-- 在这里设置表名" +
    “声明@sql 表(s varchar(1000),id int 身份)”+ Environment.NewLine +
    " " + Environment.NewLine +
        //"-- 创建语句" +
    “插入@sql(s) 值 ('create table [' + @table + '] (')” + Environment.NewLine +
    " " + Environment.NewLine +
        //"-- 列列表" +
    “插入@sql(s)”+ Environment.NewLine +
    “选择” + Environment.NewLine +
    " ' ['+column_name+'] ' + " + Environment.NewLine +
    " data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') +
    ' ' +" + Environment.NewLine +
    " 存在时的情况 (" + Environment.NewLine +
    " 从 syscolumns 中选择 id" + Environment.NewLine +
    " 其中 object_name(id)=@table" + Environment.NewLine +
    " and name=column_name" + Environment.NewLine +
    " and columnproperty(id,name,'IsIdentity') = 1 " + Environment.NewLine +
    ") 然后" + Environment.NewLine +
    " 'IDENTITY(' + " + Environment.NewLine +
    " cast(ident_seed(@table) as varchar) + ',' + " + Environment.NewLine +
    " cast(ident_incr(@table) as varchar) + ')'" + Environment.NewLine +
    " else ''" + Environment.NewLine +
    " end + ' ' +" + Environment.NewLine +
    " (当 IS_NULLABLE = 'No' then 'NOT' else '' end ) + 'NULL ' + " + Environment.NewLine +
    " 合并('DEFAULT '+COLUMN_DEFAULT,'') + ','" + Environment.NewLine +
    " " + Environment.NewLine +
    "来自 information_schema.columns where table_name = @table" + Environment.NewLine +
    " order by ordinal_position" + Environment.NewLine +
    " " + Environment.NewLine +
        //"-- 主键" +
    “声明@pkname varchar(100)”+ Environment.NewLine +
    “从 information_schema.table_constraints 中选择 @pkname = constraint_name”+ Environment.NewLine +
    “其中 table_name = @table 和 constraint_type='PRIMARY KEY'”+ Environment.NewLine +
    " " + Environment.NewLine +
    “如果(@pkname 不为空)开始”+ Environment.NewLine +
    " 插入@sql(s) 值(' PRIMARY KEY (')" + Environment.NewLine +
    "插入@sql(s)" + Environment.NewLine +
    " select '['+COLUMN_NAME+'],' from information_schema.key_column_usage" + Environment.NewLine +
    " 其中约束名称 = @pkname" + Environment.NewLine +
    " order by ordinal_position" + Environment.NewLine +
        //" -- 删除尾随逗号" +
    " 更新 @sql 集 s=left(s,len(s)-1) where id=@@identity" + Environment.NewLine +
    "插入@sql(s) 值 (')')" + Environment.NewLine +
    “结束” + Environment.NewLine +
    “其他开始” + Environment.NewLine +
        //" -- 删除尾随逗号" +
    " 更新 @sql 集 s=left(s,len(s)-1) where id=@@identity" + Environment.NewLine +
    “结束” + Environment.NewLine +
    " " + Environment.NewLine +
    "-- 右括号" + Environment.NewLine +
    “插入@sql(s) 值(')')”+ Environment.NewLine +
    " " + Environment.NewLine +
        //“ -  结果!” +
    "select s from @sql order by id";

    DataTable dt = GetTableData(Sql, ConnectionString);
    foreach(dt.Rows 中的 DataRow 行)
    {
        脚本 += 行[0].ToString() + Environment.NewLine;
    }

    返回脚本;
}




public DataTable GetTableData(string Sql, string ConnectionString)
{
    SqlConnection con = new SqlConnection(ConnectionString);
    尝试
    {
        con.Open();
        SqlCommand selectCommand = new SqlCommand(Sql, con);
        数据集数据集 = 新数据集();
        新的 SqlDataAdapter(selectCommand).Fill(dataSet);
        数据表表 = dataSet.Tables[0];
        返回表;
    }
    捕捉(例外)
    {
        返回新数据表();
    }
    最后
    {
        con.Close();
    }
}
于 2017-03-03T13:15:45.547 回答