简体   繁体   中英

Generate sql server scripts using .net framework

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" 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM