我通过右键单击数据库通过任务菜单中的生成脚本手动生成了脚本。
现在我的问题是通过 c# 代码生成该脚本...
我的问题是
是否可以通过 c# 代码生成?
给我一些提示以完成?
等待您的宝贵建议和命令。
我通过右键单击数据库通过任务菜单中的生成脚本手动生成了脚本。
现在我的问题是通过 c# 代码生成该脚本...
我的问题是
是否可以通过 c# 代码生成?
给我一些提示以完成?
等待您的宝贵建议和命令。
正如已经提到的,您可以使用 SMO 来执行此操作,这是一个使用 C# 编写数据库脚本的示例,我提到了几个选项,但正如 @David Brabant 的帖子中那样,您可以指定许多选项的值.
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();
}
此链接可以帮助您获取和编写存储过程脚本
您可以使用sql smo基本上实现 SQL Server Enterprise 管理器中可用的所有功能。这里有一个很好的教程。
编辑:在 PowerShell 中使用SMO的示例
function SQL-Script-Database
{
<#
.SYNOPSIS
Script all database objects for the given database.
.DESCRIPTION
This function scripts all database objects (i.e.: tables, views, stored
procedures, and user defined functions) for the specified database on the
the given server\instance. It creates a subdirectory per object type under
the path specified.
.PARAMETER savePath
The root path where to save object definitions.
.PARAMETER database
The database to script (default = $global:DatabaseName)
.PARAMETER DatabaseServer
The database server to be used (default: $global:DatabaseServer).
.PARAMETER InstanceName
The instance name to be used (default: $global:InstanceName).
.EXAMPLE
SQL-Script-Database c:\temp AOIDB
#>
param (
[parameter(Mandatory = $true)][string] $savePath,
[parameter(Mandatory = $false)][string] $database = $global:DatabaseName,
[parameter(Mandatory = $false)][string] $DatabaseServer = $global:DatabaseServer,
[parameter(Mandatory = $false)][string] $InstanceName = $global:InstanceName
)
try
{
if (!$DatabaseServer -or !$InstanceName)
{ throw "`$DatabaseServer or `$InstanceName variable is not properly initialized" }
$ServerInstance = SQL-Get-Server-Instance $DatabaseServer $InstanceName
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
$s = New-Object Microsoft.SqlServer.Management.Smo.Server($ServerInstance)
$db = $s.databases[$database]
$objects = $db.Tables
$objects += $db.Views
$objects += $db.StoredProcedures
$objects += $db.UserDefinedFunctions
$scripter = New-Object ('Microsoft.SqlServer.Management.Smo.Scripter') ($s)
$scripter.Options.AnsiFile = $true
$scripter.Options.IncludeHeaders = $false
$scripter.Options.ScriptOwner = $false
$scripter.Options.AppendToFile = $false
$scripter.Options.AllowSystemobjects = $false
$scripter.Options.ScriptDrops = $false
$scripter.Options.WithDependencies = $false
$scripter.Options.SchemaQualify = $false
$scripter.Options.SchemaQualifyForeignKeysReferences = $false
$scripter.Options.ScriptBatchTerminator = $false
$scripter.Options.Indexes = $true
$scripter.Options.ClusteredIndexes = $true
$scripter.Options.NonClusteredIndexes = $true
$scripter.Options.NoCollation = $true
$scripter.Options.DriAll = $true
$scripter.Options.DriIncludeSystemNames = $false
$scripter.Options.ToFileOnly = $true
$scripter.Options.Permissions = $true
foreach ($o in $objects | where {!($_.IsSystemObject)})
{
$typeFolder=$o.GetType().Name
if (!(Test-Path -Path "$savepath\$typeFolder"))
{ New-Item -Type Directory -name "$typeFolder"-path "$savePath" | Out-Null }
$file = $o -replace "\[|\]"
$file = $file.Replace("dbo.", "")
$scripter.Options.FileName = "$savePath\$typeFolder\$file.sql"
$scripter.Script($o)
}
}
catch
{
Util-Log-Error "`t`t$($MyInvocation.InvocationName): $_"
}
}
基于@Sami 答案
我已经创建了这个简单的函数,它将为您的数据库生成所有脚本(表、视图、存储过程、用户和 UserDefinedFunctions)
第一:获取所需的程序集
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies 是正确的文件夹位置(或在 64 位系统上为 C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies)。
您需要添加对以下内容的引用:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.SqlEnum.dll
二:使用这个函数
public static string ScriptDatabase()
{
// For Me Server is ".\SQLExpress" You may have changed
Server myServer = new Server(@".\SQLExpress");
Scripter scripter = new Scripter(myServer);
//Databas1 is your database Name Thats Changable
Database myAdventureWorks = myServer.Databases["MyDBName"];
/* With ScriptingOptions you can specify different scripting
* options, for example to include IF NOT EXISTS, DROP
* statements, output location etc*/
ScriptingOptions scriptOptions = new ScriptingOptions();
scriptOptions.ScriptDrops = true;
// scriptOptions.ScriptData = true;
scriptOptions.ScriptSchema = true;
scriptOptions.IncludeIfNotExists = true;
string scrs = "";
string tbScr = "";
foreach (Table myTable in myAdventureWorks.Tables)
{
/* Generating IF EXISTS and DROP command for tables */
StringCollection tableScripts = myTable.Script(scriptOptions);
foreach (string script in tableScripts)
scrs += script + "\n\n";
/* Generating CREATE TABLE command */
tableScripts = myTable.Script();
foreach (string script in tableScripts)
tbScr += script + "\n\n";
}
foreach (StoredProcedure mySP in myAdventureWorks.StoredProcedures)
{
/* Generating IF EXISTS and DROP command for StoredProcedures */
StringCollection tableScripts = mySP.Script(scriptOptions);
foreach (string script in tableScripts)
scrs += script + "\n\n";
/* Generating CREATE StoredProcedure command */
tableScripts = mySP.Script(scriptOptions);
foreach (string script in tableScripts)
tbScr += script + "\n\n";
}
foreach (View myView in myAdventureWorks.Views)
{
/* Generating IF EXISTS and DROP command for Views */
StringCollection tableScripts = myView.Script(scriptOptions);
foreach (string script in tableScripts)
scrs += script + "\n\n";
/* Generating CREATE Views command */
tableScripts = myView.Script(scriptOptions);
foreach (string script in tableScripts)
tbScr += script+"\n\n";
}
foreach (Microsoft.SqlServer.Management.Smo.User user in myAdventureWorks.Users)
{
/* Generating IF EXISTS and DROP command for Users */
StringCollection tableScripts = user.Script(scriptOptions);
foreach (string script in tableScripts)
scrs += script+"\n\n";
/* Generating CREATE Users command */
tableScripts = user.Script(scriptOptions);
foreach (string script in tableScripts)
scrs += script + "\n\n";
}
foreach (Microsoft.SqlServer.Management.Smo.UserDefinedFunction userF in myAdventureWorks.UserDefinedFunctions)
{
/* Generating IF EXISTS and DROP command for UserDefinedFunctions */
StringCollection tableScripts = userF.Script(scriptOptions);
foreach (string script in tableScripts)
scrs += script + "\n\n";
/* Generating CREATE UserDefinedFunction command */
tableScripts = userF.Script(scriptOptions);
foreach (string script in tableScripts)
scrs += script + "\n\n";
}
// For WinForms
return (scrs + "\n\n" + tbScr);
//For Console
//Console.WriteLine(scrs + "\n\n" + tbScr);
}
我刚刚使用上面的答案编写了一个命令行程序来在 c# 中执行此操作,并认为我会在上面的答案上进行一些扩展。
如果你想输出数据以及你需要使用的模式:
scripter.EnumScript(something);
//instead of
scripter.Script(something);
脚本方法只是检查 IncludeData 选项,如果设置了它就会抛出异常,但你必须上谷歌才能找到正确的方法!有趣的 API 设计!
数据库中的相关列表如下:
database.Tables
database.Schemas
database.Views
database.StoredProcedures
database.UserDefinedFunctions
database.Users
database.Roles
database.Sequences
尽管这可能并不详尽。
摆脱系统对象
这些对象中的列表都是自定义类型,IEnumerable but not IEnumerable<T>
因此您无法对它们执行 linq。这也意味着您必须找出其中的类型并使用 foreach 的隐式强制转换将它们取出。我以前从未在 c# 中使用过它,但我猜这些东西可能是针对框架 2 的。
它们中的许多也具有称为 IsSystemObject 的属性,但这并没有实现接口。起初看起来摆脱所有系统对象会很痛苦,但是您可以通过设置以下选项一举将它们全部剔除:
options.AllowSystemObjects = false;
这适用于除角色之外的所有内容,您必须手动执行系统角色:
foreach (DatabaseRole role in database.Roles)
{
if(role.IsFixedRole)
continue;
list.Add(role);
}
为输出添加对象
我使用的过程是创建一个UrnCollection,然后将不同的列表添加到集合中。像这样:
var list = new UrnCollection();
foreach (Schema schema in database.Schemas)
list.Add(schema.Urn);
//... more of these
scripter.EnumScript(list);
选项
从那里你需要弄清楚要设置哪些选项来重新创建你需要的输出。需要记住的几件事:
有关如何获取外键等的更多信息,请参阅这篇文章。
健康警告
我开始将其视为复制数据库的一种方式,因为我认为备份和恢复不会达到我想要的效果。在沿着 smo 路径走了很长一段路并遇到了很多问题之后,我进行了一些重新评估,发现备份和恢复对于那个用例来说要简单得多。
希望它会指导你和即将到来的人。
您必须在项目中添加以下四个引用以包含以下必需的命名空间
添加参考
参考 Microsoft.SqlServer.Smo.dll
命名空间
using System.Data.SqlClient;
using System.Collections.Specialized;
using Microsoft.SqlServer.Management.Smo;
现在在任何函数或按钮单击事件中使用以下代码
// For Me Server is ".\SQLExpress" You may have changed
Server myServer = new Server(@".\SQLExpress");
Scripter scripter = new Scripter(myServer);
//Databas1 is your database Name Thats Changable
Database myAdventureWorks = myServer.Databases["Database1"];
/* With ScriptingOptions you can specify different scripting
* options, for example to include IF NOT EXISTS, DROP
* statements, output location etc*/
ScriptingOptions scriptOptions = new ScriptingOptions();
scriptOptions.ScriptDrops = true;
scriptOptions.IncludeIfNotExists = true;
string scrs = "";
string tbScr = "";
foreach (Table myTable in myAdventureWorks.Tables)
{
/* Generating IF EXISTS and DROP command for tables */
StringCollection tableScripts = myTable.Script(scriptOptions);
foreach (string script in tableScripts)
scrs += script;
/* Generating CREATE TABLE command */
tableScripts = myTable.Script();
foreach (string script in tableScripts)
tbScr += script;
}
// For WinForms
MessageBox.Show(scrs + "\n\n" + tbScr);
//For Console
//Console.WriteLine(scrs + "\n\n" + tbScr);
它涉及http://www.mssqltips.com/sqlservertip/1833/generate-scripts-for-database-objects-with-smo-for-sql-server/ David Brabant 的回答(上)和上面的 SO 链接
使用代码块 2。现在你也可以使用其他人了
我在那里找不到 myserver 但在上面的代码中也解决了。
获取存储过程脚本的示例。注意:我通过字符串操作添加“GO”和“ALTER”。我花了 6 个小时试图弄清楚为什么它不生成 GO。Microsoft Strikes Back:库 SMO(服务器管理对象)很糟糕,它有缺陷且难以使用!
var dbObj = database.StoredProcedures[name, schema];
if (dbObj != null)
{
Console.WriteLine(dbObj);
var script = new StringBuilder();
script.AppendLine("USE LifelongLearning");
script.AppendLine("GO");
script.AppendLine();
StringCollection scripts = dbObj.Script(scriptOptionsCreate);
foreach (string s in scripts)
{
if (s.Contains("CREATE ", StringComparison.OrdinalIgnoreCase))
{
string s2 = s.Replace("CREATE ", "ALTER ", StringComparison.OrdinalIgnoreCase);
script.AppendLine(s2);
}
else
{
script.AppendLine(s);
}
// it's a hack because scripting of the "GO" not working well
if (s == "SET ANSI_NULLS ON" || s == "SET QUOTED_IDENTIFIER ON")
script.AppendLine("GO");
}
script.AppendLine("GO");
string fileName = schema + "." + name + ".sql";
await File.WriteAllTextAsync(folder + "\\" + fileName, script.ToString());
}
readonly static ScriptingOptions scriptOptionsCreate = new ScriptingOptions()
{
//WithDependencies = true, // will add create table before create view
IncludeHeaders = false, /****** Object: View [dbo].[v_people] Script Date: 9/30/2021 6:03:10 PM ******/
ScriptSchema = true,
ScriptData = false,
Indexes = true,
ClusteredIndexes = true,
FullTextIndexes = true,
// GO attempt
FileName = "test.sql",
ScriptBatchTerminator = true,
NoCommandTerminator = false,
//ToFileOnly = true, // it makes script empty
AppendToFile = true,
EnforceScriptingOptions = true,
AllowSystemObjects = true,
Permissions = true,
DriAllConstraints = true,
SchemaQualify = true,
AnsiFile = true,
//AnsiPadding = false,
};
完整的工作应用程序在这里: https ://github.com/sam-klok/CreateSQLScriptsFromDB/blob/main/CreateSQLScriptsFromDB/Program.cs