问题描述
我已经通过右键单击数据库,通过任务菜单中的 Generate script 手动生成了脚本。
现在我的问题是通过c#代码生成该脚本...
我的问题是
-
是否可以通过c#代码生成?
-
给我一些提示以完成操作?
p>
正在等待您的宝贵建议和命令。
如前所述,您可以使用SMO来执行此操作,下面是一个使用C#编写数据库脚本的示例,我提到了几个选项,但是正如@David Brabant的帖子中所述,您可以指定许多选项的值。
公共字符串ScriptDatabase()
{
var sb =新的StringBuilder();
var server = new Server(@ ServerName);
var databse = server.Databases [ DatabaseName];
var scripter = new Scripter(server);
scripter.Options.ScriptDrops = false;
scripter.Options.WithDependencies = true;
scripter.Options.IncludeHeaders = true;
//依此类推....
var smoObjects = new Urn [1];
foreach(databse.Tables中的表t)
{
smoObjects [0] = t.Urn;
if(t.IsSystemObject == false)
{
StringCollection sc = scripter.Script(smoObjects);
foreach(sc中的var st)
{
sb.Append(st);
}
}
}
return sb.ToString();
}
此可能会帮助您获取存储过程并为其编写脚本
i have generated scripts manually through Generate script in tasks menu by right clicking database.
Now my problem is to generate that script through c# code...
My question is
is it possible to generate through c# code?
give me some tips in order to complete?
Waiting for your valuable suggestions and commands.
As it's already mentioned, you cas use SMO to do this, here is a an example using C# to script a database, I mentioned few options, but as it is in the post of @David Brabant, you can specify the values of many options.
public string ScriptDatabase()
{
var sb = new StringBuilder();
var server = new Server(@"ServerName");
var databse = server.Databases["DatabaseName"];
var scripter = new Scripter(server);
scripter.Options.ScriptDrops = false;
scripter.Options.WithDependencies = true;
scripter.Options.IncludeHeaders = true;
//And so on ....
var smoObjects = new Urn[1];
foreach (Table t in databse.Tables)
{
smoObjects[0] = t.Urn;
if (t.IsSystemObject == false)
{
StringCollection sc = scripter.Script(smoObjects);
foreach (var st in sc)
{
sb.Append(st);
}
}
}
return sb.ToString();
}
This link may help you getting and scripting stored procedures
这篇关于以编程方式生成SQL代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!