开发者

Generate sql server scripts using .net framework

开发者 https://www.devze.com 2023-01-20 00:01 出处:网络
Is it possible to generate script from sql server using .net framework? For example, if I have database \"Northwind\". Then I wish to create/generate script insert\" 开发者_JAVA百科in form file exten

Is it possible to generate script from sql server using .net framework?

For example, if I have database "Northwind". Then I wish to create/generate script insert" 开发者_JAVA百科in form file extension .sql (ex: northwind_insert.sql).

Is something like when you using sql-server "right-click on table" > "script table as" > "Insert to" > "file".


If you add references in your code to the SMO assemblies, then you can write simple code as follows:

using Microsoft.SqlServer.Management.Smo;

namespace PlayAreaCS2010
{
    class Program
    {
        static void Main(string[] args)
        {
            var srv = new Server(@"(local)\sql2k8");
            var db = srv.Databases["TestDN"];
            foreach (Table tab in db.Tables)
            {
                foreach (string s in tab.Script())
                {
                    Console.WriteLine(s);
                }
            }
            Console.Read();
        }
    }

}

SMO Assemblies you need to reference - Microsoft.SqlServer.Smo, Microsoft.SqlServer.ConnectionInfo, Microsoft.SqlServer.Management.Sdk.Sfc - are all located in C:\Program Files\microsoft sql server\100\SDK\Assemblies (Or equivalent, adjusting for version and bitness)

0

精彩评论

暂无评论...
验证码 换一张
取 消