使用SMO程序化生成SQL Server表數據

做爲ETL的一部分,有時候就是須要把數據的Insert腳本生成出來,而後人肉拷貝到另外一個地方執行。sql

熟悉SMSS的同窗們都知道,有個生成腳本的任務,能夠生成數據庫的create腳本啊什麼的,其實也可以生產表中的數據。數據庫

自動化的ETL總不能連導出數據都人肉。。。一是容易出錯,二是太low了。ui

C#控制檯代碼能夠搞定這些,直接上代碼:spa

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management; 
using Microsoft.SqlServer.Management.Sdk.Sfc;  

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            String todayDate = DateTime.Now.Day + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year;
            String backupDirectory = "1a:\\DBBackup\\";
            String backupFileName = backupDirectory + todayDate + ".sql";
            if (File.Exists(backupFileName))
            {

                File.Delete(backupFileName);

            }
            StreamWriter sw = File.CreateText(backupFileName);


            Console.WriteLine(backupFileName);
            Console.ReadKey();            
            Console.WriteLine("hello!");


            //Console.ReadLine();
            String dbName = "2oy"; // database name   
            Server srv = new Server("3lba1");

            // Reference the database.    
            Database db = srv.Databases[dbName];

            // Define a Scripter object and set the required scripting options.   
            Scripter scrp = new Scripter(srv);
           
            scrp.Options.ScriptSchema = false;
            scrp.Options.ScriptDrops = false;
            scrp.Options.WithDependencies = false;
            scrp.Options.Indexes = false;   // To include indexes  
            scrp.Options.DriAllConstraints = false;   // to include referential constraints in the script  
            scrp.Options.ScriptData = true; //Data include!!!!!!

            
        

            //Iterate through the tables in database and script each one.

            foreach (Table tb in db.Tables)
            {

                if (!tb.IsSystemObject)
                {

                    foreach (string s in scrp.EnumScript(new Urn[] { tb.Urn }))
                    {

                        sw.WriteLine(s);

                        sw.Flush();

                    }

                }

            }


            /*
             * 此方法不能生成帶數據的腳本,可是能夠生成schema腳本
            foreach (Table tb in db.Tables)
            {
                System.Collections.Specialized.StringCollection sc = scrp.Script(new Urn[]{tb.Urn}); 

                foreach (string st in sc)
                {
                    Console.WriteLine(st);
                }
                Console.WriteLine("--");

            }
             */
             
        }
    }
}
相關文章
相關標籤/搜索