使用SMO程序化生成SQL Server表数据
作为ETL的一部分,有时候就是需要把数据的Insert脚本生成出来,然后人肉拷贝到另一个地方执行。
熟悉SMSS的同学们都知道,有个生成脚本的任务,可以生成数据库的create脚本啊什么的,其实也能够生产表中的数据。
自动化的ETL总不能连导出数据都人肉。。。一是容易出错,二是太low了。
C#控制台代码可以搞定这些,直接上代码:
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("--"); } */ } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界